> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Add Two Numbers

Leetcode Problem 2: Add Two Numbers

Problem Summary

You are given two non-empty linked lists representing two non-negative integers stored in reverse order — the head node holds the least significant digit. Add the two numbers and return the sum as a linked list in the same reversed format. Neither number has leading zeros except for the number 0 itself.

For example, adding 342 and 465:

2 -> 4 -> 3    (represents 342)
5 -> 6 -> 4    (represents 465)
= 7 -> 0 -> 8  (represents 807)

Constraints:

  • Each linked list has between 1 and 100 nodes.
  • Each node value is a single digit (0–9).
  • Neither number has leading zeros (except zero itself).

Techniques

  • Linked List
  • Math
  • Recursion

Solution

import { ListNode } from "../list-node"

function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    let currentOne: ListNode | null = l1
    let currentTwo: ListNode | null = l2
    let carry = 0
    let sumList: ListNode | null = new ListNode(-1)
    let currentSumList = sumList

    while (currentOne || currentTwo) {
        let numberOne = currentOne?.val ?? 0
        let numberTwo = currentTwo?.val ?? 0
        let sum = numberOne + numberTwo + carry
        carry = Math.floor(sum / 10)
        currentSumList.next = new ListNode(sum % 10)

        currentSumList = currentSumList .next
        currentOne = currentOne?.next ?? null
        currentTwo = currentTwo?.next ?? null
    }

    if (carry !== 0) {
        currentSumList.next = new ListNode(carry)
    }

    return sumList.next
};