Straightforward 8 line Python solution with simple logic and standard data structures


  • 0
    X
    def addStrings(self, num1, num2):
        ans, carry, num1, num2 = [], False, list(num1), list(num2)
        while num1 or num2:
            d1 = int(num1.pop()) if num1 else 0
            d2 = int(num2.pop()) if num2 else 0
            total = d1 + d2 + (1 if carry else 0)
            carry = True if total > 9 else False
            ans.append(str(total % 10))
        return ("1" if carry else "") + ("".join(ans))[::-1]

Log in to reply
 

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