Fork me on GitHub

【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 = 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?

提示:

此题的原理为“九余数定理”,即给定一个非负整数,一个数的数根(Digit Root)与它和小于它的最大的九的倍数有关。举例来说,11的数根是2,因为9+2=11。2025的数根是1,因为(2035 - 1) % 9 = 0。

基于这个定理,可以总结出求一个非负整数的数根公式如下:

代码:

class Solution {
public:
    int addDigits(int num) {
        return num - 9 * ((num - 1) / 9);
    }
};

参考:

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

 

posted @ 2015-08-17 11:37  __Neo  阅读(242)  评论(0编辑  收藏  举报