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.
ok,then,题意很简单,就是说每一位加加加,直到最后的个位数,那么最初的想法就是取余了,然后循环。
class Solution {
public:
int addDigits(int num) {
int temp[20];
while(num >= 10)
{
int i = 0;
while(num / 10 > 0)
{
temp[i] = num % 10;
num /= 10;
i++;
}
temp[i] = num;
num = 0;
for(int j = 0;j <= i;j++)
{
num += temp[j];
}
}
return num;
}
};
that’s it