Skip to content

Instantly share code, notes, and snippets.

@hongtaoh
Created October 9, 2024 22:44
Show Gist options
  • Save hongtaoh/88d44e62c788ee4fefaab04109092127 to your computer and use it in GitHub Desktop.
Save hongtaoh/88d44e62c788ee4fefaab04109092127 to your computer and use it in GitHub Desktop.
Solution to Leetcode 415 Add Strings
class Solution:
# credit: https://www.youtube.com/watch?v=q1RR8gk47Cg
def addStrings(self, num1: str, num2: str) -> str:
i = len(num1) - 1
j = len(num2) - 1
carry = 0
res = []
while i >= 0 or j >= 0:
int1 = int(num1[i]) if i >=0 else 0
int2 = int(num2[j]) if j >= 0 else 0
cur_sum = carry + int1 + int2
res.append(cur_sum % 10)
carry = cur_sum//10
i -= 1
j -= 1
if carry != 0:
res.append(carry)
final_res = [str(res[t]) for t in range(len(res)-1, -1, -1)]
return "".join(final_res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment