[Leetcode] 258. 各位相加 java

给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

示例:

输入: 38
输出: 2 
解释: 各位相加的过程为3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。

进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?

递归做法:

class Solution {
    public int addDigits(int num) {
        int temp=0;
        while(num>0){
            temp+=num%10;
            num=num/10;
         }           
        if(temp<10){
            return temp;
        }
        else{
            return addDigits(temp);
        }        
    }
}

 下面这个让人感叹数学可真神奇!对9求余就是结果了。。。

class Solution {
    public int addDigits(int num) {
        return num==0?0:(num%9==0?9:(num%9));
    }
}

猜你喜欢

转载自blog.csdn.net/niceHou666/article/details/82689330