Leetcode 415. Add Strings

Mingyu Jeon·2020년 4월 27일
0
post-thumbnail

# Runtime: 48 ms, faster than 37.48% of Python3 online submissions for Add Strings.
# Memory Usage: 14.3 MB, less than 5.55% of Python3 online submissions for Add Strings.

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        numDict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
        carry = 0
        p1 = len(num1) - 1
        p2 = len(num2) - 1
        ans = []

        while True:
            if p1 < 0 and p2 < 0:
                if carry:
                    ans.insert(0, str(carry))
                break
            if p1 < 0:
                _sum = int(num2[p2])
            elif p2 < 0:
                _sum = int(num1[p1])

            else:
                _sum = numDict[num1[p1]] + numDict[num2[p2]]

            total = _sum + carry
            carry = 0
            if total > 9:
                total -= 10
                carry = 1
            ans.insert(0, str(total))

            p1 -= 1
            p2 -= 1

        return ''.join(ans)

https://leetcode.com/problems/add-strings/submissions/

0개의 댓글