258. Add Digits

T: O(n), n is num's length

S: O(1)

class Solution {
    public int addDigits(int num) {
        int res = 0;
        while (true) {
            while (num != 0) {
                res += num % 10;
                num = num / 10;
                
            }
            //System.out.println("res:" + res);
            if (res <= 9) {
                return res;
            }
            num = res;
            res = 0; // remember to reset
            //System.out.println(num);
        }
    }
}

/*
res += 8
num = 38/10 = 3

res += 3 = 11
num = 3/10 = 0

num = 11;
res = 0;

res = 11%10 = 1
num = 11/10 = 1

res = 1%10 += 1 + 1 = 2
num = 1/10 = 0, end

return 2

*/

Digital Root

can refer:

https://ithelp.ithome.com.tw/articles/10238613

T: O(1)

S: O(1)

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

or

class Solution {
    public int addDigits(int num) {
        if(num == 0) {
            return 0;
        } else if(num % 9 == 0) {
            return 9;
        } else {
            return num % 9;
        }
    }
}

Last updated