LintCode - Add Digits(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

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

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

思路

public class Solution {
    /**
     * @param num a non-negative integer
     * @return one digit
     */
    public int addDigits(int num) {
        // Write your code here
        while(num > 9){
            int tmp = 0;
            while(num % 10 > 0 || num == 10){
                tmp += num % 10;
                num /= 10;
            }
            num = tmp;
        }
        return num;
    }
}

你可能感兴趣的:(LintCode - Add Digits(普通))