首页 > 编程语言 > 详细

Leetcode刷题记录[python]——258 Add Digits

时间:2016-05-19 19:21:41      阅读:338      评论:0      收藏:0      [点我收藏+]

一、前言

  做这题有个小收获,关于Digital root的解法,有个极方便的小公式:

技术分享

 

二、题258 Add Digits

  Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

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

  然后在做后一道关于求二叉树最大深度的问题时,参考了一些优秀的解法得到点启发,写了另一种更简单明了的解法:

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num>=10:
            re=num%10
            qu=(num-re)/10
            new_num=re+qu
            return self.addDigits(new_num)
        else:
            return num

 

Leetcode刷题记录[python]——258 Add Digits

原文:http://www.cnblogs.com/Myoungs/p/5509674.html

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