Explain digit-by-digit addition with carry.
01
01
Understand the problem
linked-listmath
02
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Stuck? AI Nudge Available
Get a conceptual hint to guide your logic without spoiling the final implementation.
03
03
Study the solution
The solution is waiting
Give it an honest attempt first — then compare your thinking with the full walkthrough.
04
04
Read the code
Digit-by-digit with carry
Run Playgroundclass ListNode:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
def add_two_numbers(l1, l2):
dummy = tail = ListNode(0)
carry = 0
while l1 or l2 or carry:
total = carry
if l1: total += l1.val; l1 = l1.next
if l2: total += l2.val; l2 = l2.next
carry, digit = divmod(total, 10)
tail.next = ListNode(digit)
tail = tail.next
return dummy.next
# --- demo --- 342 + 465 = 807 (digits stored reversed)
def build(vals):
head = None
for v in reversed(vals): head = ListNode(v, head)
return head
def to_list(head):
out = []
while head: out.append(head.val); head = head.next
return out
print(to_list(add_two_numbers(build([2, 4, 3]), build([5, 6, 4])))) # [7, 0, 8]05
05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.