AddDigits [source code]

public class AddDigits {
    public int addDigits(int num) {
        if (num < 10) return num;
        int[] digits = new int[100];
        int end = 0;
        while (num > 9) {
            digits[end++] = num % 10;
            num /= 10;
        }
        for (int i = 0; i < end; i++) num += digits[i];
        return addDigits(num);
    }
}

算法问题本身很简单, 3ms 的速度, 不算是特别快的(相对的);
如果想要改的不用 recursion, 其实也很好改. recursion 反映问题的变化的其实是 arguments, 但是如果写iteartive 的话, 只要用几个 temp var来保存这个变化的arguments 就行了. 然后本身 recursion 里面对于base 的判断, 就变成了 loop 的 header 里面对于这几个 temp 的判断; 这个思路在前面SumOfTwoIntegers或者是最简单的BinarySearch的时候都总结过;


Problem Description

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?

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

Difficulty:Easy
Category:Algorithms
Acceptance:50.93%
Contributor: LeetCode
Topics:
Math
You might like:
(E) Happy Number
Company:
Adobe Microsoft

results matching ""

    No results matching ""