Skip to main content

Add Two Numbers

Leetcode #2, "Medium": Add Two Numbers

These two people explain their solutions quite well.

General Resources about LinkedLists

Array vs LinkedList

ChatGPT solution

Below is ChatGPT's solution, with its explanation as comments, which I also like.


class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}

function addTwoNumbers(l1, l2) {
// Create a dummy head for the result linked list
let dummyHead = new ListNode(0);
let current = dummyHead; // Initialize a pointer to the current node in the result list
let carry = 0; // Initialize carry to 0

// Iterate through the input linked lists
while (l1 !== null || l2 !== null) {
// Get the values of the current nodes in l1 and l2 (or 0 if null)
let x = (l1 !== null) ? l1.val : 0;
let y = (l2 !== null) ? l2.val : 0;

// Calculate the sum of the current digits and the carry
let sum = x + y + carry;

// Update carry for the next calculation
carry = Math.floor(sum / 10);

// Create a new node with the digit part of the sum, and update the result list
current.next = new ListNode(sum % 10);
current = current.next;

// Move to the next nodes in l1 and l2 if they exist
if (l1 !== null) l1 = l1.next;
if (l2 !== null) l2 = l2.next;
}

// If there is a carry after the last addition, create a new node for it
if (carry > 0) {
current.next = new ListNode(carry);
}

// Return the result linked list (starting from the second node, as the first one is the dummy head)
return dummyHead.next;
}