/*
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
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.*/
对于小于10的直接返回,大于10的进行分割每位数字,然后加在一起,最后进行递归。
solution1
int addDigits(int num) {
if(num>=10)
{
int sum=0;
//分割数字并累加
for(;num!=0;num/=10)
sum+=num%10;
//进行递归
return addDigits(sum);
}
else
return num;
}
solution2
int addDigits(int num) {
if(num>=0&&num<10)
{
return num;
}
else
return addDigits(num%10+addDigits(num/10));
}