Problem

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

Example

Given num = 38.
The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return 2.

Challenge

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

Solution

recursive
public class Solution {
    /*
     * @param num: a non-negative integer
     * @return: one digit
     */
    public int addDigits(int num) {
        // write your code here
        if (num < 10) return num;
        int sum = 0;
        while (num != 0) {
            sum += (num%10);
            num /= 10;
        }
        return addDigits(sum);
    }
}
Non-recursive
public class Solution {
    /*
     * @param num: a non-negative integer
     * @return: one digit
     */
    public int addDigits(int num) {
        // write your code here
        while (num >= 10) {
            String cur = Integer.toString(num);
            int sum = 0;
            for (int i = 0; i < cur.length(); i++) {
                sum += Character.getNumericValue(cur.charAt(i));
            }
            num = sum;
        }
        return num;
    }
}

linspiration
161 声望53 粉丝