Python different solutions.


  • 2
    C
    def addDigits1(self, num):
        return num - ((num-1)/9)*9 if num > 0 else 0
        
    def addDigits2(self, num):
        return (num-1)%9 + 1 if num > 0 else 0
        
    def addDigits3(self, num):
        return num and (num-1)%9 + 1
      
    # Recursively  
    def addDigits4(self, num):
        if 0<= num <= 9:
            return num
        tmp = 0
        while num:
            tmp += num % 10
            num //= 10
        return self.addDigits(tmp)
        
    # Iteratively
    def addDigits(self, num):
        if num == 0:
            return 0
        while num:
            if 1 <= num <= 9:
                return num
            tmp = 0
            while num:
                tmp += num % 10
                num //= 10
            num = tmp

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.