258. Add Digits

Question 258

https://leetcode.com/problems/add-digits/description/

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?

Answer

如果不要用 loop 或 recursion 的話,可以參考 digital root 的規則 --> https://en.wikipedia.org/wiki/Digital_root

也就是取除以 9 後的餘數,就可以得到最後的 digit。 不過要注意的是有例外:

  • 當輸入的數字本身就是 9 的倍數時,ex,9 % 9 = 0,這是錯的 需要判斷後將其設為 9

int addDigits(int num) {
    int result = num % 9;
    return (result != 0 || num == 0 ) ? result : 9;
}

Last updated