LeetCode刷題Easy篇 Add Digits
阿新 • • 發佈:2018-12-20
題目
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
Example:
Input:38
Output: 2 Explanation: The process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
十分鐘嘗試
利用遞迴呼叫,除以10,對10求mod獲取每位數字,邏輯不是問題,已經一遍ok,程式碼如下,但是題目的followup需要研究一下,先上一個遞迴版本:
class Solution { public int addDigits(int num) { int res=caculate(num); if(res/10==0){ return res; } return addDigits(res); } private int caculate(int num){ int res=0; while(num>0){ res+=num%10; num=num/10; } return res; } }
非遞迴非迴圈解法
class Solution {
public int addDigits(int num) {
return 1 + (num - 1) % 9;
}
}