mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-16 23:16:26 +00:00
feat(work): implement correct addTwoNumbers algorithm for linked list addition
This commit is contained in:
@@ -53,9 +53,18 @@ class Solution:
|
|||||||
def addTwoNumbers(
|
def addTwoNumbers(
|
||||||
self, l1: Optional[ListNode], l2: Optional[ListNode]
|
self, l1: Optional[ListNode], l2: Optional[ListNode]
|
||||||
) -> Optional[ListNode]:
|
) -> Optional[ListNode]:
|
||||||
head = ListNode()
|
|
||||||
|
dummy = ListNode()
|
||||||
carry = 0
|
carry = 0
|
||||||
l1curr = head
|
curr = dummy
|
||||||
l2curr = head
|
while l1 or l2 or carry:
|
||||||
while head:
|
s = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
|
||||||
l1.val + l2.val
|
carry, val = divmod(s, 10)
|
||||||
|
|
||||||
|
curr.next = ListNode(val)
|
||||||
|
curr = curr.next
|
||||||
|
|
||||||
|
l1 = l1.next if l1 else None
|
||||||
|
l2 = l2.next if l2 else None
|
||||||
|
|
||||||
|
return dummy.next
|
||||||
|
|||||||
Reference in New Issue
Block a user