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;
}
};

本文介绍了一种数字压缩算法,该算法通过反复将一个非负整数的各位数字相加直至结果仅剩一位数来实现。例如,对于数字38,经过3+8=11和1+1=2两步操作后得到最终结果2。
122

被折叠的 条评论
为什么被折叠?



