2. Add Two Numbers Leetcode solution in JavaScript (JS)

0

Problem:

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.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

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]

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.

Solution:

Brute force solution for beginners with separate functions for everything in a meaningful manner.

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let firstnumber = "";
    let secondnumber = "";
    while(l1){
        firstnumber = firstnumber+""+l1.val;
        l1 = l1.next;
    }
    while(l2){
        secondnumber = secondnumber+""+l2.val;
        l2 = l2.next;
    }
    let sum = BigInt(reversestringandreturnint(secondnumber)) + BigInt(reversestringandreturnint(firstnumber));
   
    return linkedListFromArray(stringtoarray(sum+""));
   
};
function reversestringandreturnint(str){
    let rev = "";
if(str){
    for(let i = str.length -1;i>=0;i-- ){
        rev = rev+""+str[i];
    }
}
return rev;
}
function stringtoarray(str){
    //reverse and convert to array
    let arr = new Array();
    if(str){
    for(let i = str.length -1;i >=0;i--){
        arr.push(str[i]);
    }
}

return arr;
}
function linkedListFromArray(a) {    
    for (let i=0; i<a.length; i++) {
        a[i] = new ListNode(a[i]);
        if (i!=0 && i<a.length) {
            a[i-1].next = a[i];
        } else {
            a[i].next = null;
        }
    }

    return a[0];
}
function toNum(n) {
   var nStr = (n + ""); 
   if(nStr.indexOf(".") > -1) 
      nStr = nStr.replace(".","").replace(/\d+$/, function(m){ return --m; });
   return nStr.replace(/(\d+)e\+?(\d+)/, function(m, g1, g2){
      return g1 + new Array(+g2).join("0") + "0";
   })
}

Optimized solution using recursion for advanced developers :

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    const iter = (n1, n2, rest = 0) => {
        if (!n1 && !n2 && !rest) return null;
        const newVal = (n1?.val || 0) + (n2?.val || 0) + rest;
        const nextNode = iter(n1?.next, n2?.next, Math.floor(newVal / 10));
        return new ListNode(newVal % 10, nextNode);
    }
    return iter(l1, l2);
};

Leave a Comment

Skip to content