05 August 2008
Given a non-negative integer
, repeatedly add all its digits until the result has only one digit.1
num
Example:
1
2
3
4
Input: 38
Output: 2
Explanation: 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?
这个题比较简单,follow up是常数级的复杂度;如果用正常的loop或者递归的话是线性时间复杂度,因此需要略微取巧。
正常的loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int addDigits(int num) {
if (num < 10) {
return num;
}
int temp = num;
int result = 0;
while (true) {
while (temp != 0) {
result += temp % 10;
temp /= 10;
}
if (result < 10) {
return result;
} else {
temp = result;
result = 0;
}
}
}
}
递归
1
2
3
4
5
6
7
8
class Solution {
public int addDigits(int num) {
if (num < 10) {
return num;
}
return addDigits(num % 10 + num / 10);
}
}
接下来看常数的解法,对9进行取模,当作9进制来算(证明略),参考这里
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int addDigits(int num) {
if (num < 10) {
return num;
} else if (num % 9 == 0) {
return 9;
} else {
return num % 9;
}
}
}