码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Add Digits

时间:2015-08-17 13:31:52      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

 

【LeetCode】Add Digits

标签:

原文地址:http://www.cnblogs.com/jdneo/p/4735817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!