1、题目描述
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.
2、Java实现
public class Solution {
public int addDigits(int num) {
return 1+(num-1)%9;
}
}
3、经验教训
第一眼看到题目觉得没什么头绪,后来发现还是亘古不变的找规律:
input: 0 1 2 3 4 …
output: 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 ….
For base b (decimal case b = 10), the digit root of an integer is:
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
or
dr(n) = 1 + (n - 1) % 9