l258 add digits

题目描述

1
2
3
4
5
6
7
8
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?

解题思路

L258

Go递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func addDigits(num int) int {
s:=0

for num>0 {
s += num%10
num /= 10
}

if s<10 {
return s
}else{
return addDigits(s)
}
}

Go实现O(1)算法

1
2
3
func addDigits(num int) int {
return 1 + (num - 1) % 9
}