LeetCode之Add Digits
1、题目
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.
2、代码实现
public class Solution {
public int getAllSum(int val) {
int sum = 0;
while (val > 0) {
sum += val % 10;
val /= 10;
}
return sum;
}
public int addDigits(int num) {
if (num <= 0)
return 0;
while (num >= 10) {
num = getAllSum(num);
}
return num;
}
}
赞 (0)
