258. Add Digits
- Total Accepted: 110807
- Total Submissions: 224904
- Difficulty: Easy
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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
思考:使用递归循环计算每次的每位和,直到为一位时返回。
public class Solution {
public int addDigits(int num) {
if(num/10 == 0){
return num;
}
int ret = 0;
while(num != 0){
ret += num%10;
num /= 10;
}
return addDigits(ret);
}
}