2. Add Two Numbers


Problem

https://leetcode.com/problems/add-two-numbers/

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Solution

  • Mind the last carry
  • All numbers in JavaScript are double-precision floating-point numbers. Use Math.floor()
  • Always use new ListNode so that l1 and l2 won't be affected
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {

    let carry = 0
    let p1 = l1
    let p2 = l2
    let doAdd = function() {
        if (p1 && p2) {
            let sum = p1.val + p2.val + carry
            carry = Math.floor(sum / 10)

            p1 = p1.next
            p2 = p2.next

            return new ListNode(sum % 10)
        } else {
            let p = p1? p1 : p2
            let sum = p.val + carry
            carry = Math.floor(sum / 10)

            if (p1) { p1 = p1.next }
            else { p2 = p2.next }

            return new ListNode(sum % 10)
        }
    }

    let result = doAdd()
    let p = result

    while(p1 || p2) {
        p.next = doAdd()
        p = p.next
    }

    if (carry > 0) {
        p.next = new ListNode(carry)
    }

    return result
};

results matching ""

    No results matching ""