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 = 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?

Hint:

A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.

the simpler solution, is to use recursion/loop, each time, add all digits number, until generates a single digit number.

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

        return num;

    }
}

There a a constant solution, the result set can only be in [0...9], 0 can only be generated by 0, so the result set of all positive number is [1...9], each time the number increase by 10, the number that adds up to 9 shift left by 1, say res(18) = 9, res(27) = 9, ... so this question becomes : how many numbers are there between this number and the last res(X) = 9;

so the question becomes X = 9 * ((num-1)/9) and the final result is num - X;

public class Solution {
    public int addDigits(int num) {
        return num - 9 * ((num-1)/9);
    }
}

results matching ""

    No results matching ""