Overview
The objective is to repeatedly add all digits of a number until the result is only a single digit.
For example
Input: 453
Step 1: 4+5+3 = 12
Step 2: 1+2 =3
Output: 3
Another example
Input: 45
Step 1: 4+5 = 9
Output: 9
Program
Here is the program for the same
package main
import "fmt"
func addDigits(num int) int {
if num < 10 {
return num
}
for num > 9 {
num = sum(num)
}
return num
}
func sum(num int) int {
output := 0
for num > 0 {
output = output + num%10
num = num / 10
}
return output
}
func main() {
output := addDigits(453)
fmt.Println(output)
output = addDigits(45)
fmt.Println(output)
}
Output
3
9