kucheasysa

Algoverse_adesh_44

Jul 13th, 2024
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
  8.         current = ListNode(0)
  9.         tail = current
  10.         carry = 0
  11.  
  12.         while l1 is not None or l2 is not None or carry != 0:
  13.             digit1 = l1.val if l1 is not None else 0
  14.             digit2 = l2.val if l2 is not None else 0
  15.  
  16.             sum = digit1 + digit2 + carry
  17.             digit = sum % 10
  18.             carry = sum // 10
  19.  
  20.             newNode = ListNode(digit)
  21.             tail.next = newNode
  22.             tail = tail.next
  23.  
  24.             l1 = l1.next if l1 is not None else None
  25.             l2 = l2.next if l2 is not None else None
  26.  
  27.         result = current.next
  28.         current.next = None
  29.         return result
  30.        
Advertisement
Add Comment
Please, Sign In to add comment