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.
The formula is:
or,
class Solution {
public:
int addDigits(int num) {
return 1+(num-1)%9;
}
};
本文介绍了一种高效的算法,用于将任意非负整数连续加和其各位数字,直至结果为一位数。通过数学归纳法证明了算法的正确性,并提供了O(1)运行时间的实现方式。
1307

被折叠的 条评论
为什么被折叠?



