问题
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...
似乎可以看出,结果就是余9的数字。用35478验证一下,结果是9,余9是0。不对,应该要对9的倍数特殊对待:9的倍数的结果就是9.
要点
找规律
时间复杂度
O(1)
空间复杂度
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;
}
};