問(wèn)題
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Could you do it without any loop/recursion in O(1) runtime?
例子
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
分析
1=>1 2=>2 3=>3 4=>4 5=>5 6=>6 7=>7 8=>8 9=>9 10=>1 12=>2...
似乎可以看出,結(jié)果就是余9的數(shù)字。用35478驗(yàn)證一下,結(jié)果是9,余9是0。不對(duì),應(yīng)該要對(duì)9的倍數(shù)特殊對(duì)待:9的倍數(shù)的結(jié)果就是9.
要點(diǎn)
找規(guī)律
時(shí)間復(fù)雜度
O(1)
空間復(fù)雜度
O(1)
代碼
分類討論
class Solution {
public:
int addDigits(int num) {
return num != 0 && num % 9 == 0 ? 9 : num % 9;
}
};
合并情況
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}
};