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.

用一个循环加递归可以暴力解

public int addDigits(int num) {
    if (num < 10) {
        return num;
    }
    int result = 0;
    while (num > 0) {
        result += num % 10;
        num = num / 10;
    }
    result = addDigits(result);
    return result;
}

然后发现其实没必要,这个计算过程就是求数根 Digital Root 参考Wikipedia 直接有一个公式 dr(n) = 1 + ((n-1) % 9)

直接O(1)解决了

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