leetcode解题之各位相加

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

示例:

输入: 38
输出: 2 
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
进阶: 你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

很明显不会使用O(1)的方法,先给个递归的方式吧

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

学习一下大神们O(1)的写法

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

具体解释请参考官方题解和评论

发布了98 篇原创文章 · 获赞 0 · 访问量 3997

猜你喜欢

转载自blog.csdn.net/l888c/article/details/104501149