题目:
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) {
int i=1;
if(num>=10){
i++;
}
int tmp = num;
while(tmp/10>=10){
i++;
tmp/=10;
}
int[] array = new int[i];
int sum = 0;
for(i=0;i<array.length;i++){
sum =sum+num%10;
num = num/10;
}
if(sum>=10){
sum = addDigits(sum);
}
return sum;
}
}