【LeetCode解题报告】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 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:

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

Hint: 

https://en.wikipedia.org/wiki/Digital_root


从维基百科中得出结论:(num-i)%9 == 0 满足此条件的i就是num的数字根(digital root)

我们可以举几个例子简单验证一下:

首先无论是多少位的数,都会变成两位数或者一位数的形式,且最终一定会变成一位数的形式:

10=9+1, 11=9+2, 12=9+3, 13=9+4, 14=9+5, 15=9+6, 16=9+7, 17=9+8, 18=9+9, 19=9+9+1=2*9+1, ……, num=k*9+i

所以,思路就变得非常简单:

①如果输入的数字小于10,则直接返回,这个数本身就是自己的树根

②如果输入的数字大于等于10:若它能不能被9整除,则返回其除以9的余数;否则返回9

程序如下:

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值