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?
一刷
题解:Digit Root解法
如果进制为b(这道题中为10),输入为n, digit root of n is:
- dr(n) = 0 if n==0
- dr(n) = (b-1) if n!=0 and n%(b-1) == 0
- dr(n) = n % (b-1) if n % (b-1)!=0
或者: - dr(n) = 1 + (n-1) % (d-1)
因为:
dr(abc) = (a*10^2 + b*10 + c)%9 = (a+b+c)%9
public class Solution {
public int addDigits(int num) {
return 1 + (num - 1) % 9;
}
}