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?

solution 1

int addDigits(int num) {
    if(num) {
        int res = num % 9;
        return (res == 0)? 9:res;
    } else {
        return num;
    }
}

solution 2

int addDigits(int num) {
    int res = num % 9;
    return (res != 0 || num == 0)? res:9;
}

solution 3

int addDigits(int num) {
        return (num - 1) % 9 + 1;
}

//根据同余定理10^n ≡ 1 (mod 9)得a_n10^n + … + a_110 + a_0 ≡ a_n + … + a_1 + a_0 (mod 9)
//其中a_n表示位数的系数,综上所述,取模后能够得到各个位数系数和,且这系数和是小于9的整数
//当且仅当n对9取模为零时侯要分开考虑,n%9 = 0 ,当给的num是0是,返回值才为0,否则返回9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值