Python solution with detailed explanation


  • 0
    G

    Solution

    Add Strings https://leetcode.com/problems/add-strings/?tab=Description

    1. Easy algorithm - just start from last character.
    2. Make sure you use carry information correctly.
    class Solution(object):
        def addStrings(self, num1, num2):
            """
            :type num1: str
            :type num2: str
            :rtype: str
            """
            N, M = len(num1), len(num2)
            i,j = N-1, M-1
            result, carry = [], 0
            while i >= 0 or j >= 0:
                if i >= 0 and j >= 0:
                    s = int(num1[i]) + int(num2[j]) + carry
                    s, carry = s%10, s//10
                    result.append(str(s))
                    i,j= i-1, j-1 
                elif i >= 0:
                    s = int(num1[i]) + carry
                    s, carry = s%10, s//10
                    result.append(str(s))
                    i= i-1 
                elif j >= 0:
                    s = int(num2[j]) + carry
                    s, carry = s%10, s//10
                    result.append(str(s))
                    j = j-1 
            if carry:
                result.append(str(carry))
            result.reverse()
            return "".join(result)
    

Log in to reply
 

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