258. Add Digits - jiejackyzhang/leetcode-note GitHub Wiki

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

Follow up:

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

##Approach 1 这道题目采用循环或者递归,非常trivial。

public class Solution {
    public int addDigits(int num) {
        while(num >= 10) {
            num = addAllDigits(num);
        }
        return num;
    }
    
    private int addAllDigits(int num) {
        int res = 0;
        while(num != 0) {
            res += num % 10;
            num /= 10;
        }
        return res;
    }
}

##Approach 2 Wikipedia article

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