Leetcode Algorithm for Adding Two Numbers

Recently, I attempted the following leetCode Problem:

However, I encountered an issue where one of my test cases failed and I'm unsure why.

Here is the scenario:

You are provided with two non-empty linked lists that represent two non-negative integers. The digits are stored in reverse order, with each node containing a single digit. Your task is to add the two numbers and return the result as a linked list.

You can assume that the numbers do not contain any leading zeros, except for the number 0 itself.

To tackle this problem, I devised the following algorithm:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
const makeLinkedList = (inArr, i) => {
    if (i < 0) return null
    return { val:inArr[i], next:makeLinkedList(inArr, i-1)}
}


var addTwoNumbers = function(l1, l2) {
    let sum = 0
    let i = 1
    while(l1 || l2) {
        if (l1 && l2) {
            sum = sum + l1.val*i + l2.val*i
             l1 = l1.next
             l2 = l2.next
        } else {

        if (l1) {  
            sum = l1.val*i + sum
            l1 = l1.next
        }
        if (l2) {
            sum = l2.val*i + sum
            l2 = l2.next
        }    
      }
        i = i*10
    }
    const sumToString = sum.toLocaleString('fullwide', {useGrouping:false}); 
    return  makeLinkedList(sumToString, sumToString.length-1)
};

The reason behind using a while loop instead of recursive functions in the code above was mainly for optimization purposes.

However, I faced a challenge as my test case failed for the input below:

[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[5,6,4]

My output returned as [0,3,NaN,NaN,1], rather than

[6,6,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
.

If anyone could assist me in identifying why my input might be failing, it would be greatly appreciated.

Answer №1

When JavaScript converts a number into scientific notation, it will include a "+" sign for positive exponents. The output you are seeing is "1E+30", with the "NaN"s representing the symbols "+" and "E" (in reverse order). Simply by using a console log of either "sum" or "sumToString", you could have easily identified this issue without prior knowledge.

Not all programming languages disclose their maximum precision values, but JavaScript does through Number.MAX_SAFE_INTEGER, which holds the value "9 007 199 254 740 991". This is slightly more than "9E+15", but significantly less than "1 + 1E+30" (the longer number).

The correct approach is to add the numbers as taught in elementary school – adding two digits, writing one digit, and carrying over if there is a remainder to the next set of digits to be added.

Iterative method:

function createLinkedList(arr, index) {
  index = index || 0;
  return index < arr.length ? { val: arr[index], next: createLinkedList(arr, index + 1) } : null;
}

var addTwoNumbers = function(l1, l2) {
  var dummyNode = { next: null };
  var current = dummyNode;
  var carry = 0;
  
  while (l1 || l2 || carry) {
    current.next = { next: null };
    current = current.next;
    
    var sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
    
    if (sum < 10) {
      current.val = sum;
      carry = 0;
    } else {
      current.val = sum - 10;
      carry = 1;
    }
    
    l1 = l1 ? l1.next : null;
    l2 = l2 ? l2.next : null;
  }
  
  return dummyNode.next;
}

var numA = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
var numB = [5, 6, 4];
console.log(addTwoNumbers(createLinkedList(numA), createLinkedList(numB)));

numA = [9, 9];
numB = [1, 9];
console.log(addTwoNumbers(createLinkedList(numA), createLinkedList(numB)));

Recursive method:

function createLinkedList(arr, index) {
  index = index || 0;
  return index < arr.length ? { val: arr[index], next: createLinkedList(arr, index + 1) } : null;
}

var addTwoNumbers = function(l1, l2, carry) {
  if (!(l1 || l2 || carry))
    return null;
    
  carry = carry || 0;
  var sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
  
  return {
    val: sum % 10,
    next: addTwoNumbers(l1 ? l1.next : null, l2 ? l2.next : null, sum > 9 ? 1 : 0)
  };
}

numA = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
numB = [5, 6, 4];
console.log(addTwoNumbers(createLinkedList(numA), createLinkedList(numB)));

numA = [9, 9];
numB = [1, 9];
console.log(addTwoNumbers(createLinkedList(numA), createLinkedList(numB)));

Answer №2

JavaScript solution to address a specific issue.

var addNumbers = function (num1, num2) {
 let remainder = 0;
 let number1Node = num1;
 let number2Node = num2;

 let list = new ListNode(0);
 let currentNode = list;

 while (number1Node || number2Node) {
    const valueNum1 = number1Node ? number1Node.val : 0;
    const valueNum2 = number2Node ? number2Node.val : 0;
    let sum = valueNum1 + valueNum2 + remainder;
    remainder = 0;
    if (sum > 9) {
        remainder = Math.floor(sum / 10);
        sum = sum % 10;

    }

    currentNode.next = new ListNode(sum);
    currentNode = currentNode.next;

    number1Node = number1Node ? number1Node.next : null;
    number2Node = number2Node ? number2Node.next : null;
 }

if (remainder != 0) {
    currentNode.next = new ListNode(remainder);
    currentNode = currentNode.next;
}


return list.next;

};

function ListNode(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}

const num1 = new ListNode(2, new ListNode(4, new ListNode(3)));
const num2 = new ListNode(5, new ListNode(6))
const result = addNumbers(num1, num2);

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with ng-true-value in AngularJS version 1.6.1 - not functioning as expected

Recently, I delved into AngularJS and followed an online tutorial that showcased how to utilize ng-true-value and ng-false-value. Here's the snippet: <!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis ...

Get the package from a Lerna-managed monorepository using a git URL

Currently working on a project using yarn. The project has a dependency that is part of a larger monorepo managed by lerna. Despite the subpackage being updated, it has not been published yet and I require access to that unreleased code. Is there a method ...

Syntax for private members in ES6 classes

I'm curious to know the most efficient way to declare private members within ES6 classes. In simpler terms, what is the best practice for implementing: function MyClass() { var privateFunction = function() { return 0; }; this.publicFuncti ...

checkbox appear based on vue condition

I have checkboxes on my list that are always checked, but I only want them to be checked if the associated object's property "include" is set to true. Currently, all the checkboxes are checked by default, and when I click on them, they uncheck and ex ...

The text loader feature in THREE.js is failing to load

My first attempt at coding THREE.js resulted in a black screen when I tried to load the Text loader. Can someone help me resolve this issue? I kept getting the following error even after multiple attempts: three.module.js:38595 GET 404 (Not Found) ...

Guide on producing a milky overlay using Vue js

Currently, I am utilizing Vue 3 along with Bootstrap 5 in my project. In my application, there is a button and two input fields. Upon clicking the button, I would like to display a "milky" overlay as shown in this example: https://i.sstatic.net/K21k8.png ...

What is the best way to toggle an element's visibility using the select tag?

Let me break down the issue for you. In my HTML code, I have a select element that looks like this: <select id="seasons" multiple="multiple"> <option value="s01">Season 1</option> <option value="s02">Season 2</option> ...

The process of obtaining and sending a token from an HTML page while submitting a form request to a Laravel 5 application involves a few key steps

My application consists of the client side being written in HTML and Angularjs, while the server-side is using Laravel 5. Every time I submit my form, I send the models using $http to a route in my Laravel 5 app, but I continuously encounter the error: pr ...

Deactivate a <tr> element if any of its <td> cells contain a value

In my table, there are various trs and tds with different element names. I need to determine if there is text in a specific field. If there is text, I want to disable or hide the entire tr to prevent user interaction. Unfortunately, I am unable to provide ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Converting large JSON data (approximately 100MB) into an Excel file using JavaScript

As a beginner in the realm of REST technology, I find myself navigating through a JSON response received from a server and showcasing the data on the client side. Currently, I am faced with handling approximately 22MB of JSON data that needs to be exporte ...

What is causing the check box in the simple_form view to consistently return a value of 1 when checked or unchecked in rails 3.2?

A checkbox with the name "need_delivery" is used to determine whether the next two text boxes should be displayed. These two text boxes are enclosed within a div with the id of task_request_delivery. Below is the code snippet in the simple_form view named ...

Returning a PHP variable to AJAX communication

if($rx==$_SESSION['randomx'] and $ry==$_SESSION['randomy']){ echo "Congratulations, you hit the correct cell! You only used:".$_SESSION['poskus']; } else{ $distance=sqrt(($rx-$_SESSION['randomx'])*($rx-$_ ...

Javascript's asynchronous initiator

Starting a variable synchronously has been a common practice. const x = call_a_sync_function(); However, issues arise when the initiator switches to async. const x = await call_an_async_function(); // SyntaxError: Unexpected reserved word I experimente ...

Tips for utilizing ajax function to refresh database entries

I am working with a customer information table that is populated from a database. The last column in this table contains an edit button which, when clicked, shows a popup window with text fields pre-filled with database values. I want users to be able to u ...

Set up a trigger to activate when a WordPress User Role is selected, or alternatively, execute JavaScript

Looking for a solution to detect when a new user is created with a custom User Role set to lessee. Options include adding a trigger through WordPress filters or actions, or detecting the change in JavaScript using an event listener. I have identified the ...

What could be causing this code to malfunction on a mobile device?

I am struggling to make this drag and drop function work on mobile devices. Despite implementing the code, it doesn't seem to function properly when accessed on my mobile phones. Here is the snippet of the code: copy = 1; $('.dragArea img&apo ...

Ever since updating my Node JS, the functionality of the MaterializeCSS carousel methods has ceased to work

Recently, I encountered some issues with my React project that features a materialize-css carousel. The problem arose after updating my nodeJS version from 14.8.1 to 16.13.0. Specifically, these errors kept popping up: TypeError: Cannot read properties o ...

Determine the total of the final column in recently added rows by utilizing JavaScript

I have a table where users can dynamically add rows as needed. I am looking to implement a feature that will display the total of the last column in a text box underneath the table using JavaScript. If real-time calculations are not feasible, then I am ope ...

Building an HTTP request and response directly from an active socket in a Node.js environment

My current project involves passing HTTP requests to a child process in Node.js. I am struggling with passing the active Socket using child.send('socket', req.socket). Once inside the child process, I need to recreate the HTTP request and respons ...