[LeetCode#258]Add Digits

Problem:

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

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

Analysis:

Note: all digits problem could be solved through underlying principle!
For this problem, the best reference is:
https://en.wikipedia.org/wiki/Digital_root

The meaning of Digital root is, it actually measures the distance between num and the largest number(the largest multiple of 9 before it).
E:
The digital root of 11 is 2, the largest multiple of 9 before it is 9, the ditance is 11 - 9 = 2(just equal to digital root!)
Thus we could directly compute digital root through the minus operation between num, and its leftmost mutiple of 9.
The larget multiple of 9 before a number.
9 * ((num - 1) / 9)

use (num-1) is to in case num is just the largest multiple of 9. 
for other cases, it is actually equal to num/9

Solution:

public class Solution {
    public int addDigits(int num) {
        if (num < 0)
            throw new IllegalArgumentException("the passed int num is illegal!");
        return num - 9*((num-1)/9);
    }
}
原文地址:https://www.cnblogs.com/airwindow/p/4774854.html