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:
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
//思路首先:朴素的理想将数num的各个位提取出来,然后相加。如果只有一位就终止每一位的相加
//
class Solution {
public:
int addDigits(int num) {
int ans=0, cnt=2;
while(cnt>1)
{
cnt=0;//判断当前这个数num的位数
ans=0;
//取出个位数相加
while(num)
{
ans+=num%10;; //总是取出个位数
num=num/10;
cnt++;
}
if(cnt == 1)
break;
num =ans;//重新以和来取个位数相加
}
return ans;
}
};
别人家的解法1:递归解法,思路清晰简单
class Solution {
public:
int addDigits(int num) {
int sum=0;
while(num){
sum=sum+num%10;
num=num/10;
}
if(sum<10){
return sum;
}
else{
return addDigits(sum);
}
}
};
参考资源:
【1】网友,shensccs,博文地址,http://blog.csdn.net/shensccs/article/details/48469573
原文:http://blog.csdn.net/ebowtang/article/details/50417277