Show problems as
Classic problem #445MediumLinked ListMathStack

Add Two Numbers II

Real-world version: Add Two Digit Strips
Tracked in this browser only
Read Add Two Numbers II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Two whole numbers reach you as digit strips. A strip is a list of single digits written the way you would read the number off a page, most significant digit first, so [3, 0, 6] stands for three hundred and six. A strip always holds at least one digit, and the only strip that may open with a 0 is the single-digit strip [0].

Return the sum of the two numbers as a strip in the same format: most significant digit first, and with no leading zeros.

The strips stand in for singly linked lists, which can only be walked from the most significant digit onwards. Reach the low-order digits with a stack or by reversing rather than pasting the digits together into one integer value.

Examples

Example 1

Input
first = [4,5,6], second = [7,8]
Output
[5, 3, 4]

The strips stand for 456 and 78. Their sum is 534, written as the strip [5,3,4].

Example 2

Input
first = [9,9], second = [1]
Output
[1, 0, 0]

99 plus 1 is 100, so the answer strip is one digit longer than either input strip.

Example 3

Input
first = [0], second = [7]
Output
[7]

0 plus 7 is 7, a single-digit strip.

Example 4

Input
first = [3,0,6], second = [1,9,4]
Output
[5, 0, 0]

306 plus 194 is 500, written as [5,0,0].

Constraints

  • 1 <= first.length, second.length <= 100
  • 0 <= first[i], second[i] <= 9
  • Neither strip has a leading zero, except for the strip [0] itself.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def add_two_numbers(first: list[int], second: list[int]) -> list[int]:
Java
public int[] addTwoNumbers(int[] first, int[] second)