Skip to content

Latest commit

 

History

History
37 lines (35 loc) · 965 Bytes

415. Add Strings.md

File metadata and controls

37 lines (35 loc) · 965 Bytes

415. Add Strings

  1. clarify,
  2. make sure nothing is off
  3. short demo.
  4. writing code
  5. 2 short demo again. for corner cases.
class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        if not num1 and not num2:
            return ''
        elif not num1:
            return num2
        elif not num2:
            return num2
        len1, len2 = len(num1), len(num2)
        carry = 0
        ans = ''
        i, j = len1 - 1, len2 - 1
        while i >= 0 or j >= 0 or carry:
            if i >= 0:
                carry += int(num1[i])
            # i for num1, j for num2
            if j >= 0:
                carry += int(num2[j])
            digit_sum = carry % 10 
            carry = carry // 10 
            ans = str(digit_sum) + ans
            i -= 1
            j -= 1
        # the following 2 lines can be moved to while loop condition.
        # if carry:
        #     ans = '1' + ans
        return ans