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

一、前言

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

formula of the 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
原文地址:https://www.cnblogs.com/Myoungs/p/5509674.html