LeetCode题解:Add Digits

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.

题意:给定非负整数,不断把各位数字相加,直到结果是个位数。例如38,处理过程是:3+8=11,1+1=2,2为返回值。

解决思路:最终数字和不可能大于10,最大值为9,猜测运算和模9运算有关,果然是求该整数除以9的余数。

public class Solution {
    public int addDigits(int num) {
        return (num - 1) % 9 + 1;
    }
}

你可能感兴趣的:(LeetCode题解:Add Digits)