415. Add Strings - LeetCode Solution


String

Python Code:

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        ptr1 = len(num1) - 1
        ptr2 = len(num2) -1

        carry = 0
        res = ""

        while ptr1 >=0 or ptr2 >= 0:

            if ptr1 < 0:
                a = str( int(num2[ptr2]) + carry)
            elif ptr2 <0:
                a = str(int(num1[ptr1]) + carry)
            else:
                a = str(int(num1[ptr1]) + int(num2[ptr2]) + carry)


            if len(a) == 2:
                carry = int(a[0])
                res += a[1]
            else:
                carry= 0
                res+=a

            if ptr2 >=0:
                ptr2-=1
            if ptr1>=0:
                ptr1-=1
        
        
        if carry!= 0:
            res+= str(carry)

        return res[::-1]


Comments

Submit
0 Comments
More Questions

1245C - Constanze's Machine
1005A - Tanya and Stairways
1663F - In Every Generation
1108B - Divisors of Two Integers
1175A - From Hero to Zero
1141A - Game 23
1401B - Ternary Sequence
598A - Tricky Sum
519A - A and B and Chess
725B - Food on the Plane
154B - Colliders
127B - Canvas Frames
107B - Basketball Team
245A - System Administrator
698A - Vacations
1216B - Shooting
368B - Sereja and Suffixes
1665C - Tree Infection
1665D - GCD Guess
29A - Spit Problem
1097B - Petr and a Combination Lock
92A - Chips
1665B - Array Cloning Technique
1665A - GCD vs LCM
118D - Caesar's Legions
1598A - Computer Game
1605A - AM Deviation
1461A - String Generation
1585B - Array Eversion
1661C - Water the Trees