Easy to understand by padding the inputs, in Python


  • 0
    F
    class Solution(object):
        def addStrings(self, num1, num2):
            """
            :type num1: str
            :type num2: str
            :rtype: str
            """
            carry = 0
            ans = ""
            # align two nums
            if len(num1) > len(num2):
                num2 = '0' * (len(num1) - len(num2)) + num2
            elif len(num2) > len(num1):
                num1 = '0' * (len(num2) - len(num1)) + num1
            for i in reversed(range(len(num1))):
                a = ord(num1[i]) - ord('0')
                b = ord(num2[i]) - ord('0')
                ans = chr((a + b + carry) % 10 + ord('0')) + ans
                carry = (a + b + carry) // 10
            if carry:
                ans = chr(carry + ord('0')) + ans
            return ans
    

Log in to reply
 

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