- Problem:
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
. Since2
has only one digit, return it.Follow up:
Could you do it without any loop/recursion in O(1) runtime?
- analysis:
1 首先题目要求不能用循环和递归要注意
2 已知: (x + y) % z = (x % z + y % z) % z
x % z % z = x % z
假如有这么一个数ABCDE,有ABCDE=A*10000+B*1000+C*100+D*10+E=(A+B+C+D+E)+(A*9999+B*999+C*99+D*9),那么ABCDE%9=(A+B+C+D+E)%9,这就很好的实现了ABCDE%9的结果为一位数,但是这里还需要注意一点,(A+B+C+D+E)%9若为1,则结果为0。因而可用ABCDE%9=(A+B+C+D+E-1)%9+1,这就完美解决了问题。
- anwser:
public class Solution {
public int addDigits(int num) {
return (num-1) % 9 + 1;
}
}