DEV Community

JP Antunes
JP Antunes

Posted on

Add two numbers

Leetcode time again!

This one actually took me a bit. The problem description states we should sum two non-empty linked lists representing two positive integers stored in reverse order, and return the result as a linked list.

The sum can exceed JS's Max Integer size and that means that adding the numbers requires some type coercion between string and BigInt but it replaces a loop with a simple arithmetic addition so it seemed worth it.

var addTwoNumbers = function(l1, l2) {
  let num1Str = '';
  let num2Str = '';
  let node = l1;

  while (node) {
    num1Str = node.val + num1Str;
    node = node.next;
  }

  node = l2;
  while (node) {
    num2Str = node.val + num2Str;
    node = node.next;
  }

  const sum = BigInt(num1str) + BigInt(num2str);  
  const sumStr = sum.toString();
  const resLst = new ListNode(sumStr[sumStr.length - 1]);

  node = resLst;
  for (let i = sumStr.length - 2; i >= 0; i--) {
    node.next = new ListNode(sumStr[i]);
    node = node.next;
  }
  return resLst;   
};

//Runtime: 96 ms, faster than 99.18% of JavaScript online submissions for Add Two Numbers.
//Memory Usage: 39.2 MB, less than 13.89% of JavaScript online submissions for Add Two Numbers.

Top comments (0)