Straight forward python solution


  • 0

    Carry forward based, set1 is the longer input string while set2 is the shorter input string.

    class Solution(object):
        def addStrings(self, num1, num2):
            """
            :type num1: str
            :type num2: str
            :rtype: str
            """
            res = ""
            carry = 0
            set1, set2 = (num1, num2) if len(num1) > len(num2) else (num2, num1) 
            for i in range(len(set1)):
                if i < len(set2):
                    tmp = ord(set1[-1-i]) + ord(set2[-1-i]) - 96 + carry
                else:
                    tmp = ord(set1[-1-i]) + 0 - 48 + carry
                if tmp > 9:
                    carry = 1
                    res = chr(tmp - 10 + 48) + res 
                else:
                    carry = 0
                    res = chr(tmp + 48) + res
            return "1" + res if carry else res
    

Log in to reply
 

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