258. Add Digits
阿新 • • 發佈:2019-02-06
題目
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.
我的解法
演算法分析:方法的目的就是num的位元數字和,若小於10則return,若大於10則求和後再遞迴呼叫此方法。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); } }
答案解法(數學規律,沒看懂)
public class Solution {
public int addDigits(int num) {
return num==0?0:(num%9==0?9:(num%9));
}
}
演算法分析:利用數學規律,技巧性太強。