Advertisement
hoangreal

Add 2 Strings

Oct 19th, 2024
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | Source Code | 0 0
  1. class Solution:
  2.     def add_two_lists(self, list1: list[str], list2: list[str]) -> str:
  3.         from collections import deque
  4.         answers = deque([])
  5.         remainder = 0
  6.  
  7.         i1 = len(list1) - 1; i2 = len(list2) - 1
  8.         while True:
  9.             # Base
  10.             if i1 < 0 and i2 < 0:
  11.                 break
  12.  
  13.             num1 = int(list1[i1]) if not (i1 < 0) else 0
  14.             num2 = int(list2[i2]) if not (i2 < 0) else 0
  15.  
  16.             total = num1 + num2 + remainder
  17.             next_digit, remainder = total % 10, total // 10 # max total = 18
  18.             answers.appendleft(str(next_digit))
  19.  
  20.             i1 -= 1; i2 -= 1
  21.         if remainder > 0:
  22.             answers.appendleft(str(remainder))
  23.  
  24.         return "".join(answers)
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement