LeetCode-258 Add Digits

来源:互联网 发布:倒班表软件 编辑:程序博客网 时间:2024/06/06 11:49

https://leetcode.com/problems/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?


1、知识点:Digital Root(数根)

一个数的数根等于它对9取模;特殊情况:该数为9的倍数时,其数根为9。

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

http://baike.baidu.com/link?url=1-CBAkwvBe4Qd1elJ-6ILT2pE9bX4DZzjvKRMNi1137G4_1Pf66Jxlp-O8r-GORul4EsfxEdV_GdNbI13aoUkK

2、(12ms)

class Solution {

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

};

3、(8ms)

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

4、(8ms)

class Solution {
public:
    int addDigits(int num) {
        return (num-1)%9+1; // 其中,%运算的结果符号与被除数符号一致,故 -1%9 = -1
    }
};

0 0
原创粉丝点击