Java/258.Add Digits 各位相加

本文介绍了两种快速计算数字和的算法。第一种算法通过循环迭代将整数分解为各位数字并累加,直至得到一位数结果。第二种算法采用数学公式,直接通过取模运算计算数字的根号和,效率高达100%。这些算法对于处理大量数字求和问题提供了高效的解决方案。

题目


 

 

 

代码部分一(5ms 42.26%)

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

 

 

代码部分二(1m's 100%)

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值