DEV Community

loading...
Cover image for Solving LeetCode - Add Two Numbers

Solving LeetCode - Add Two Numbers

phariale profile image pharia-le ・2 min read

Question

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

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

Let's Go!

Solve by using PREP.

  • P - Two non-empty linked lists representing two non-negative integers.
  • R - Return a linked list of the two numbers added
  • E - Examples provided by question. (See Above)
  • P - See Below

Before I knew about Node List...

var addTwoNumbers = function(l1, l2) {
    const reverseOfL1 = reverseArr(l1)
    const reverseOfL2 = reverseArr(l2)
    let list = []
    let carry = 0

    for (let i=0; i<l1.length; i++) {
        const sum = reverseOfL1[i] + reverseOfL2[i]
        if (sum > 9) {
            list.push(sum%10+carry)
            carry = 1
        } else {
            list.push(sum+carry)
            carry = 0
        } 
    }

    return list
}

function reverseArr(arr) {
    return arr.reduce((newArr,num) => {
      newArr.unshift(num)
      return newArr
    }, [])
}

Enter fullscreen mode Exit fullscreen mode

Realizing my mistake and reading up on NodeList and Linked Lists. Answer below:

let addTwoNumbers = function(l1, l2) {
    let dummyHead = new ListNode(0);
    let p1 = l1;
    let p2 = l2;
    let current = dummyHead;
    let carry = 0;

    while (p1 !== null || p2 !== null) {
        let x = (p1 !== null) ? p1.val : 0;
        let y = (p2 !== null) ? p2.val : 0;
        let sum = x + y + carry;

        carry = Math.floor(sum / 10);
        current.next = new ListNode(sum % 10);
        current = current.next;

        if (p1 !== null) {
            p1 = p1.next;
        }
        if (p2 !== null) {
            p2 = p2.next;
        }
    }

    if (carry > 0) {
        current.next = new ListNode(1);
    }

    return dummyHead.next;
};

Enter fullscreen mode Exit fullscreen mode

Conclusion

& Remember... Happy coding, friends! =)

Sources

Discussion (0)

pic
Editor guide