搜索
您的当前位置:首页正文

LeetCode刷题:各位相加

来源:易榕旅网

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

示例:

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

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

题解:
这道题很适合递归,采取递归方法进行。
时间和内存消耗为:

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Top