[leetcode]add digits

题目描述

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?

Hint:

1. A naive implementation of the above process is trivial. Could you come up with other methods?
2. What are all the possible results?
3. How do they occur, periodically or randomly?
4. You may find this Wikipedia article useful.

代码

直接用程序的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class  {
public int addDigits(int num) {
String str = String.valueOf(num);
char[] digits = str.toCharArray();

while(true) {
int sum = 0;
for (int i = 0; i < digits.length; i++) {
sum += Character.getNumericValue(digits[i]);
}

if(sum < 10){
return sum;
}
digits = String.valueOf(sum).toCharArray();
}
}
}

其实这里是有公式计算的:(,详见维基百科Digital root。公式如下:

1
2
3
dr(n) = 0 if n == 0
dr(n) = (b-1) if n != 0 and n % (b-1) == 0
dr(n) = n mod (b-1) if n % (b-1) != 0

或者:

1
dr(n) = 1 + (n - 1) % 9

所以程序很简单:

1
2
3
4
5
public class {
public int addDigits(int num) {
return 1 + (num - 1) % 9;
}
}