Finish problem 0002-add-two-numbers

This commit is contained in:
Johan Sandoval
2026-07-21 21:51:26 -05:00
parent 2476821049
commit def79644a1
2 changed files with 51 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode | None, l2: ListNode | None) -> ListNode | None:
dummy = ListNode()
curr = dummy
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
digit = (v1 + v2 + carry) % 10
carry = (v1 + v2 + carry) // 10
curr.next = ListNode(digit)
curr = curr.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next
@@ -0,0 +1,30 @@
import pytest
from solution import ListNode, Solution
def build(vals):
head = None
for v in reversed(vals):
head = ListNode(v, head)
return head
def to_list(node):
out = []
while node:
out.append(node.val)
node = node.next
return out
@pytest.mark.parametrize(
"l1,l2,expected",
[
([2, 4, 3], [5, 6, 4], [7, 0, 8]),
([0], [0], [0]),
([9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9], [8, 9, 9, 9, 0, 0, 0, 1]),
],
)
def test_add_two_numbers(l1, l2, expected):
result = Solution().addTwoNumbers(build(l1), build(l2))
assert to_list(result) == expected