mediumLinked ListMath 0 views

Add Two Numbers as Linked Lists

Add two non-negative integers stored as reverse-order digit linked lists and return the sum in the same format.

You are given two singly-linked lists, l1 and l2, each representing a non-negative integer. The digits are stored in reverse order: the head of each list holds the least-significant digit, and each node holds a single digit from 0 to 9.

Add the two numbers together and return the sum as a linked list, using the same reverse-digit format.

You may assume neither input represents a number with a leading zero, except for the number 0 itself (represented as a single node holding 0).

Example 1

Input: l1 = [2,4,3], l2 = [5,6,4]

Output: [7,0,8]

Explanation: 342 + 465 = 807, stored digit-by-digit in reverse order.

Example 2

Input: l1 = [9], l2 = [1]

Output: [0,1]

Explanation: 9 + 1 = 10, which needs an extra leading digit.

Example 3

Input: l1 = [0], l2 = [0]

Output: [0]

Constraints

  • The number of nodes in each list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • Neither list contains a leading zero, except the list [0] itself, which represents the number zero.

Follow-up

Could you solve this if the digits were stored in forward order (most-significant digit first) instead? How would your approach need to change?

Hints

Companies

No companies reported yet.

Discussion

Sign in to join the discussion.

Loading discussion...

Test results

No test cases yet.