258. Add Digits

本文介绍了一种快速计算数字根的方法,即不断累加一个非负整数的所有位数直到结果仅有一位数的过程。通过数学方法避免使用循环或递归,在O(1)时间内完成计算。具体方法为取n除以9的余数,并对特殊情况作出调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

s思路:
1. 如何下手?不用loop.也就是说不能一位一位的取,不用考虑细节的来做,方法就两种,不是bottom-up,就是top-down.
2. 这就是说用一个top-down的系统方法,一般数学的方法就比较好:参考了https://en.wikipedia.org/wiki/Digital_root
3. 就是n%9的余数,如果余数等于0,就返回9.所以修正一下就是:(n-1)%9+1
4. 应该能猜测到,最后结果是0-9,所以才都可以猜一下用余数

class Solution {
public:
    int addDigits(int num) {
        if(num<1) return num;
        return (num-1)%9+1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值