Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Add Two Numbers

LeetCode #2Medium
Elementary addition · carry

Two non-negative numbers are stored as linked lists of digits in reverse order. Add them and return the sum as a linked list, also in reverse order.

Asked atAmazonMicrosoftBloombergAdobe
step 1 / 6
num 1 (342)
num 2 (465)
2
4
3
5
6
4
[0][1][2][3][4][5]
result
Elementary addition · carry
1dummy ← node; tail ← dummy; carry ← 0
2while l1 or l2 or carry:
3 sum ← (l1.val or 0) + (l2.val or 0) + carry
4 carry ← sum / 10
5 tail.next ← node(sum % 10); tail ← tail.next
6 advance l1 and l2 if present
7return dummy.next
state
  • num 1342
  • num 2465
  • carry0

line 1Each list holds the digits of a number in REVERSE order, so index 0 is the ones place. Add them exactly like grade-school addition: walk both lists together, summing one column at a time and carrying the overflow.