Tom on the Internet
← Back

Add Two Numbers

medium
Linked List

Challenge

You are given two non-empty linked lists, l1 and l2, where each represents a non-negative integer. The digits are stored in reverse order, e.g. the number 321 is represented as 1 -> 2 -> 3 -> in the linked list. Return the sum of the two numbers as a linked list.

<Code />

addTwoNumbers(l1, l2) {
    let head = l1;
    while (true) {
      l1.val += l2.val;

      if (l1.val > 9) {
          l1.val -= 10;
          l1.next ??= new ListNode(0);
          l1.next.val++
      }

      if (!l1.next && !l2.next) {
          break;
      }

      l1.next ??= new ListNode(0);
      l2.next ??= new ListNode(0);
      l1 = l1.next;
      l2 = l2.next;
    }

    return head;
}

Thoughts

This one was simple enough that I could complete it without looking up the solution. Some say it's more of an easy than a medium. The trick is realizing that, because you are given the numbers in reverse order, you can just do simple addition like you were taught in grade school. Example: 1 -> 5 -> 2 4 -> 7 -> 6 is the same as 251 +674 1 + 4 = 5 7 + 5 = 12 (move 1 to next column) 8 + 2 + 1 = 9 9 2 5