不废话:
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?
Hint:
- A naive implementation of the above process is trivial. Could you come up with other methods?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
class Solution {
public:
int addDigits(int num) {
if(num==0){return 0;}
return ((num-1)%9+1);
}
};
重点和技巧是上面的(num-1)%9+1
关于数论,有下面技巧:
ab=a*10+b;
ab%9=(a*9+a+b)%9=(a+b)%9
同理之下:
abc=a*100+b*10+c
abc=(a*99+b*9+a+b+c)%9=(a+b+c)%9
(自然数mod(9)后是0~8,而当需要输出1~9时,可以先mod(9)再整体+1)