Skip to the code
cf.
+25 XP

#243 Add Big Counters Digit by Digit

medium

A metrics service stores huge counters as linked lists of digits, most significant digit first, so 7 -> 2 -> 4 -> 3 is 7243. The counters can have more digits than a JavaScript number can hold exactly.

Write addCounters(a, b) that returns the sum as a new list in the same format. Neither input has leading zeros, except the number 0 itself, which is a single node 0. Don't convert the whole counter to a number.

Example 1

Input: a = [7,2,4,3], b = [5,6,4]
Output: [7,8,0,7]

7243 + 564 = 7807.

Example 2

Input: a = [2,4,3], b = [5,6,4]
Output: [8,0,7]

243 + 564 = 807.

Constraints

  • Each list has 1 to 100 nodes.
  • 0 <= node.val <= 9

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).