LeetCode (258):Add Digits

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?


這是一個數學問題(廢話),寫下幾個例子你會發現每個結果都是num mod 9後的餘數。

我的代碼:

 1 public class Solution {
 2     public int addDigits(int num) {
 3        if(num%9==0&&num>9){
 4             return 9;
 5         }
 6         if(num>=10){
 7             num=num%9;
 8         }
 9         return num;
10     }
11 }

這是我一開始的代碼,其實我只是想解決下邊界問題。之後看了網上的代碼,頓時感覺我的代碼有點傻。

修改後:

 public class Solution {
 2     public int addDigits(int num) {
 3      return 1+(num-1)%9;
10     }
11 }

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章