[리트코드] 415. Add Strings - python 본문

코테 문제 풀이

[리트코드] 415. Add Strings - python

미니모아 2022. 4. 12. 23:52
반응형

415. Add Strings

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        carry = 0
        res = []
        p1 = len(num1) - 1
        p2 = len(num2) - 1
        
        while p1 >= 0 or  p2 >= 0:
            
            if p1 < 0 :
                n1 = 0 
            else:
                n1 = num1[p1]
            
            if p2 < 0 :
                n2 = 0
            else:
                n2 = num2[p2]
            
            tmp = int(n1) + int(n2) + carry
            carry = tmp // 10
            res.append(str(tmp % 10))
            
            p1 -= 1
            p2 -= 1
        
        if carry:
            res.append(str(carry))
        return ''.join(res[::-1])
반응형
Comments