관리 메뉴

솜씨좋은장씨

[leetCode] 415. Add Strings (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 415. Add Strings (Python)

솜씨좋은장씨 2020. 9. 5. 22:07
728x90
반응형

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

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Solution

class Solution(object):
    def addStrings(self, num1, num2):
        answer_list = []
        carry = 0
        index1, index2 = len(num1), len(num2)
        while index1 or index2 or carry:
            digit = carry
            if index1:
                index1 -= 1
                digit += int(num1[index1])
            if index2:
                index2 -= 1
                digit += int(num2[index2])
            carry = digit > 9
            answer_list.append(str(digit % 10))
        return ''.join(answer_list[::-1])

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments