题面:
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?
题解:将每个数的各个位上的数字加起来,若大于9,则继续加,个位数则输出。则自然可想到,模除和累加,一个while即可。做完后觉得很笨。思考后则可得任何大于9得数按此法即是求对9的模。则可更简便。
class Solution {
public:
int addDigits(int num) {
while(num>9){
int sum=0;
while(num){
sum+=num%10;
num/=10;
}
num=sum;
}
return num;
}
};
class Solution {
public:
int addDigits(int num) {
return(1+(num-1)%9);
}
};