首页 > 其他 > 详细

258. Add Digits

时间:2016-02-26 20:34:44      阅读:218      评论: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 = 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?

树根问题,参考https://zh.wikipedia.org/wiki/%E6%95%B8%E6%A0%B9

树根的用途:

数根可以计算模运算同余,对于非常大的数字的情况下可以节省很多时间

数字根可作为一种检验计算正确性的方法。例如,两数字的和的数根等于两数字分别的数根的和。

另外,数根也可以用来判断数字的整除性,如果数根能被3或9整除,则原来的数也能被3或9整除。

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num == 0: return 0
        else:
            return num - 9 * ((num - 1) / 9)

258. Add Digits

原文:http://www.cnblogs.com/sxbjdl/p/5221476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!