题目原址:https://leetcode.com/problems/add-digits/?tab=Description
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?
这道题的关键在于题目要求时间复杂度为O(1), 显然一般的方法是做不到的,这里我们用 repeated digital sum,也叫 digital root 算法直接求解。
Congruence formula:
f(num)=1+(num−1)%9
关于这个算法的详细介绍,大家可以看wiki,讲的非常清楚:
https://en.wikipedia.org/wiki/Digital_root
最后附上代码片段:
class Solution {
public:
int addDigits(int num)
{
return 1 + ((num - 1) % 9);
}
};