Add Strings

Problem Id: 415 Difficulty: Easy


Intuition

Solution


class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        num1 = list(num1[::-1])
        num2 = list(num2[::-1])
        if len(num1) > len(num2):
            num1, num2 = num2, num1

        up = 0
        ans = []
        for i in range(len(num1)):
            n1, n2 = int(num1[i]), int(num2[i])
            tmp = up + n1 + n2
            up = tmp // 10
            ans.append(str(tmp % 10))

        for i in range(len(num1), len(num2)):
            n2 = int(num2[i])
            tmp = up + n2
            up = tmp // 10
            ans.append(str(tmp % 10))

        if up:
            ans.append('1')

        return ''.join(ans[::-1])