258. Add Digits
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.
Since 2 has only one digit, return it.
Follow up: Could you do it without any loop/recursion in O(1) runtime?
Solution
首先要想到這問題就是問%9的結果。 EX: 38 => 11 => 2 == (11%9) == (38%9) 然後問題就單純了,只要濾掉 num!=0 && num%9 == 0 的case(此時應該是9), 其他就是num%9維結果。
public int addDigits(int num) {
if(num == 0) return 0;
if(num%9 == 0) return 9;
return num%9;
}
Last updated
Was this helpful?