Leetcode - 258 - Add Digits

<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px; background-color: rgb(255, 255, 255);">For example:</span>

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

内容来源:https://leetcode.com/problems/add-digits/

最好想到的方法是递归演示,找到最后答案:
class Solution {
public:
    int addDigits(int num) {
        int tmp = 0;
        while (num > 9) {
            while (num > 0) {
                tmp += num % 10;
                num /= 10;
            }
            num = tmp;
        }
        return num;
    }
};
不过结果显示超时了。
第二种方法,看到提示,可以在O(1)的时间内完成,然后从10开始依次寻找规律,发现结果是(num - 1) % 9 + 1,
class Solution {
public:
    int addDigits(int num) {
        return (num - 1) % 9 + 1;
    }
};
结果显示运行时间8ms AC。
然后看到C统计,有5ms AC的答案,所以好想知道怎么实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值