Python straightforward and neat solution with divmod


  • 0
    A
    def addStrings(self, num1, num2):
            result = ''
            carry = 0
            i = 0
            j = 0
            while i < len(num1) or j < len(num2):
                digit1 = 0
                if i < len(num1):
                    digit1 = ord(num1[-i-1]) - ord('0')
                digit2 = 0
                if j < len(num2):
                    digit2 = ord(num2[-j-1]) - ord('0')
                carry, digit = divmod(digit1 + digit2 + carry, 10)
                result = chr(ord('0') + digit) + result
                i += 1
                j += 1
            if carry == 1:
                result = '1' + result
            return result
    

Log in to reply
 

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