问题描述
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?
解决方法
要求复杂度为O(1),参考https://leetcode.com/problems/add-digits/discuss/:
The essence of this problem is that 10^n ≡ 1 (mod 9), and thus a_n10^n + … + a_110 + a_0 ≡ a_n + … + a_1 + a_0 (mod 9). This process can be continued until a number less than 9 is gotten, i.e. num % 9. For any digit n, n = n % 9 unless n = 9. The only confusing case is n % 9 = 0, but addDigits(num) = 0 if and only if num = 0, otherwise it should be 9 in fact.
以38为例,38 = 3*10+8 3+8=11 1+1=2 其中,3*10+8≡3+8(mod 9) 1*10+1≡1+1(mod 9),所以求解的过程即不断取余的过程,所以得到以下代码(特殊情况为rem正好为9,此时单独判断):
class Solution
{
public static int addDigits(int num)
{
int rem = num % 9;
return (num == 0 || rem != 0) ? rem : 9;
}
}