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.
//给定一个非负整数num,重复地将其每位数字相加,直到结果只有一位数为止。
class Solution{
public:
int addDigits(int num){
while (num > 9){
int c = 0;
while (num > 0){
c = c + num % 10;
num = num / 10;
}
num = c;
}
return num;
}
};