Advertisement
kosievdmerwe

Untitled

Mar 9th, 2022
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. #     def __init__(self, val=0, next=None):
  4. #         self.val = val
  5. #         self.next = next
  6. class Solution:
  7.     def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
  8.         ans = None
  9.         end = None
  10.         carry = 0
  11.         while l1 is not None or l2 is not None:
  12.             n1 = 0 if l1 is None else l1.val
  13.             l1 = None if l1 is None else l1.next
  14.             n2 = 0 if l2 is None else l2.val
  15.             l2 = None if l2 is None else l2.next
  16.            
  17.             new_num = n1 + n2 + carry
  18.             carry = new_num // 10
  19.             new_num %= 10
  20.            
  21.             # print(n1, n2, new_num, carry)
  22.            
  23.             if end is not None:
  24.                 end.next = ListNode(new_num)
  25.                 end = end.next
  26.             else:
  27.                 ans = ListNode(new_num)
  28.                 end = ans
  29.                
  30.         if carry != 0:
  31.             end.next = ListNode(carry)
  32.            
  33.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement