题目
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
解题思路
循环累加每一位,时间复杂度O(logN)
不需要循环,递归的暂时没想到,/(ㄒoㄒ)/~~
代码
addDigits.go
package _258_Add_Digits
func AddDigits(num int) int {
for ;num >= 10; {
var sum int
for ;num >= 10; {
sum += num % 10
num = num / 10
}
num += sum
}
return num
}
测试
addDigits_test.go
package _258_Add_Digits
import "testing"
func TestAddDigits(t *testing.T) {
var tests = []struct{
num int
output int
}{
{38, 2},
{10, 1},
}
for _, test := range tests {
ret := AddDigits(test.num)
if ret == test.output {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", test.output, ret)
}
}
}