Intermediate Level

Implement the addTwoNumbersLinkedList method that adds two numbers represented by linked lists and returns the result list.

The input contains two linked lists represented as integer arrays a and b. Each array stores the digits of a non-negative number in reverse order.

Your task is to add both numbers and return the result as another array in the same reverse-order format.

For example, [2,4,3] represents 342, and [5,6,4] represents 465. Their sum is 807, so the returned array is [7,0,8].

Example 1

Input
a (int[]) = [2,4,3]
sizeA (int) = 3
b (int[]) = [5,6,4]
sizeB (int) = 3
Returns (int[]) [7,0,8]

Example 2

Input
a (int[]) = [0]
sizeA (int) = 1
b (int[]) = [0]
sizeB (int) = 1
Returns (int[]) [0]

Example 3

Input
a (int[]) = [9,9,9]
sizeA (int) = 3
b (int[]) = [1]
sizeB (int) = 1
Returns (int[]) [0,0,0,1]

Add the digits the same way we add numbers manually from right to left. Because the digits are already stored in reverse order, start from index 0 of both arrays.

At each step, add the current digit from the first list, the current digit from the second list, and the carry from the previous step. Store sum % 10 in the result and carry forward sum / 10.

Continue until both arrays are fully processed and no carry remains.

Pseudocode:

function addTwoNumbersLinkedList(a, sizeA, b, sizeB):
    result = empty array
    carry = 0
    i = 0
    while i < sizeA or i < sizeB or carry > 0:
        sum = carry
        if i < sizeA:
            sum = sum + a[i]
        if i < sizeB:
            sum = sum + b[i]
        append sum % 10 to result
        carry = sum / 10
        i++
    return result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.