Given a non-negative integernum, repeatedly add all its digits until the result has only one digit.

For example:

Givennum = 38, the process is like:3 + 8 = 11,1 + 1 = 2. Since2has only one digit, return it.

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

Credits:
Special thanks to@jianchao.li.fighterfor adding this problem and creating all test cases.

Subscribeto see which companies asked this question.

Hide Tags

Math

Hide Similar Problems

(E) Happy Number


public class Solution {
    public int addDigits(int num) {
        /**
         * 12,345 = 1 × (9,999 + 1) + 2 × (999 + 1) + 3 × (99 + 1) + 4 × (9 + 1) + 5 
         * 12,345 = (1 × 9,999 + 2 × 999 + 3 × 99 + 4 × 9) + (1 + 2 + 3 + 4 + 5)
         * 
         */
        return (num == 0) ? 0 : (num % 9 == 0 ? 9 : num % 9);
    }
}

results matching ""

    No results matching ""