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.
参考维基百科上的https://en.wikipedia.org/wiki/Digital_root
这是一个求一个数的树根的问题,通过观察找规律可以发现一个数的树根就是这个数(num-1)%9+1的结果
![](https://upload.wikimedia.org/math/d/8/1/d81a3418905afba963286aa00504a275.png)
class Solution {
public:
int addDigits(int num) {
return (num-1)%9+1;
}
};