Source:
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: 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?
这题很有意思,普通做法就是log级别的复杂度,按题目说法一直循环操作即可。
代码:
class Solution {
public:
int addDigits(int num) {
int ans=0;
int tmp=num;
while(tmp>0){
ans+=tmp%10;
tmp/=10;
if(tmp==0 && ans/10>0){
tmp=ans;
ans=0;
}
}
return ans;
}
};
官网上给出了更优的方法(https://leetcode.com/articles/add-digits/):
这个叫做digital root,有这样的公式
基本原理:一个能被9整除的数,各位数字之和能被9整除。
所以
实现上,最后两种情形可以合为一种:
代码:
class Solution {
public:
int addDigits(int num) {
return num==0?0:1+(num-1)%9;
}
};
时空复杂度均为 O ( 1 ) O(1) O(1)。