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?
分析:
各位数字相加,直到只有一位即可。若n/10不为0,则一直将各位相加即可。
解法一:
class Solution {
public:
int addDigits(int num) {
while(num/10)
{
num = num/10 + num%10;
}
return num;
}
};
如果不用循环,那可能就是有相关规律,计算发现10~18的结果是1~9,所以9个数字一循环。对于小于9的数直接除以9求余数即可;对于大于等于9的数,可以用(n-1)%9+1来解决。
解法2:
class Solution {
public:
int addDigits(int num) {
if(num==0)
return 0;
else
return 1+(num-1)%9;
}
};