【LeetCode】258. 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.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

解决方法

要求复杂度为O(1),参考https://leetcode.com/problems/add-digits/discuss/
The essence of this problem is that 10^n ≡ 1 (mod 9), and thus a_n10^n + … + a_110 + a_0 ≡ a_n + … + a_1 + a_0 (mod 9). This process can be continued until a number less than 9 is gotten, i.e. num % 9. For any digit n, n = n % 9 unless n = 9. The only confusing case is n % 9 = 0, but addDigits(num) = 0 if and only if num = 0, otherwise it should be 9 in fact.
以38为例,38 = 3*10+8 3+8=11 1+1=2 其中,3*10+8≡3+8(mod 9) 1*10+1≡1+1(mod 9),所以求解的过程即不断取余的过程,所以得到以下代码(特殊情况为rem正好为9,此时单独判断):

class Solution
{
    public static int addDigits(int num)
    {
        int rem = num % 9;
        return (num == 0 || rem != 0) ? rem : 9;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大师兄电子工作室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值