Question:
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.
(1)首先是得到每位数字之和,用while语句实现(内循环)
(2)判断每位数字之和是否是个位数,若不是则继续计算每位数字之和,while语句实现(外循环)
class Solution {
public:
int addDigits(int num) {
int add;
while( num > 9 )
{
add = 0;
while(num > 9)
{
add = add +num%10;
num = num/10;
}
num = add + num;
}
return num;
}
};