258. Add Digits

循环:

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num >= 0 and num < 10:
            return num
        while num > 9:
            temp = 0
            while num:
                temp += num % 10
                num =  num / 10
            num = temp
        return num

这个办法很神奇

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        snum = str(num)
        if len(snum) == 1:
            return int(snum)
        s = 0
        for n in snum:
            s += int(n)
            if s > 9:
                s -= 9
        return s
        

你可能感兴趣的:(258. Add Digits)