题目
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. Since2 has only one digit, return it.
我的解法
public class Solution {
public int addDigits(int num) {
if(num < 10)
return num;
int res = 0;
while(num >= 10){
res += num % 10;
num = num / 10;
}
return addDigits(res + num);
}
}
算法分析:方法的目的就是num的比特数字和,若小于10则return,若大于10则求和后再递归调用此方法。
答案解法(数学规律,没看懂)
public class Solution {
public int addDigits(int num) {
return num==0?0:(num%9==0?9:(num%9));
}
}
算法分析:利用数学规律,技巧性太强。