Using Javascript to multiply strings

While working on the leetcode problem related to multiplication, I encountered an interesting issue.

Given two non-negative integers num1 and num2 represented as strings, the task is to return the
product of these two numbers, also in string form.

However, there is a constraint: We cannot utilize any built-in BigInteger library or directly convert the inputs into integers.

Example 1:

Input: num1 = "2", num2 = "3" 
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456" 
Output: "56088"

Constraints:

- The lengths of num1 and num2 are between 1 and 200.
- Both num1 and num2 consist only of digits.
- Neither num1 nor num2 have any leading zeros, except for the number 0 itself.

To approach this problem, I followed these steps:

  1. Convert the strings to integers.
  2. Multiply the integers.

The algorithm used for this process is as follows:

const numberMap = {
    "0": 0,
    "1": 1, 
    "2": 2,
    "3": 3, 
    "4": 4,
    "5": 5,
    "6": 6,
    "7": 7, 
    "8": 8, 
    "9": 9
}
var multiply = function(num1, num2) {
    let i = num1.length
    let j = num2.length 
    let sum = currentPower = 0
    let firstNumber = secondNumber = 0
    while(i > 0 || j > 0) {
        const firstNum = i > 0 ? (numberMap[num1[i-1]]) * (10**currentPower) : 0
        const secondNum = j > 0 ? (numberMap[num2[j-1]]) * (10**currentPower) : 0 
        firstNumber += firstNum
        secondNumber += secondNum
        currentPower++
        i--
        j--
    }

    sum = firstNumber * secondNumber
    return sum.toString()
 }; 

However, when testing with the input:

"123456789"
"987654321"

The output obtained was ""121932631112635260" instead of ""121932631112635269"". How can this be corrected?

Answer №1

One method involves multiplying each individual digit by every other digit and utilizing the index as the position.

This process is similar to manual multiplication, where you would do:

1  2  3  4  *  4  3  2  1
-------------------------
               1  2  3  4
            1  4  6  8
         3  6  9 12
      4  8 12 16
-------------------------
      5  3  2  2  1  1  4

In this approach, the arrays of strings are reversed, and the final result set is also reversed.

Prior to returning the result, the array goes through a filtering process to remove any leading zeros.

function multiply(a, b) {
    var aa = [...a].reverse(),
        bb = [...b].reverse(),
        p = [],
        i, j;

    for (i = 0; i < aa.length; i++) {
        for (j = 0; j < bb.length; j++) {
            if (!p[i + j]) p[i + j] = 0;
            p[i + j] += aa[i] * bb[j];
            if (p[i + j] > 9) {
                if (!p[i + j + 1]) p[i + j + 1] = 0;
                p[i + j + 1] += Math.floor(p[i + j] / 10);
                p[i + j] %= 10;
            }
        }
    }
    return p
        .reverse()
        .filter((valid => (v, i, { length }) => valid = +v || valid || i + 1 === length)(false))
        .join('');
}

console.log(multiply('2', '3'));     //     6
console.log(multiply('123', '456')); // 56088
console.log(multiply('9133', '0'));  //     0
console.log(multiply('9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', '9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'));

Answer №2

function performMultiplication() {
    var input1 = document.getElementById('numberA').value;
    var input2 = document.getElementById('numberB').value;
    var lengthInput1 = input1.length;
    var lengthInput2 = input2.length;
    var resultArray = [];
    var product = 0;
    var carry = 0;

    resultArray.length = lengthInput1 + lengthInput2;
    // initialize array elements to 0
    resultArray.fill(0);

    // iterate over string in reverse
    for (var i = lengthInput1 - 1; i >= 0; i--) {
        for (var j = lengthInput2 - 1; j >= 0; j--) {
            // calculate product of digits at each position
            product = (input1.charCodeAt(i) - 48) * (input2.charCodeAt(j) - 48); 
            sum = resultArray[i + j + 1] + product;
            resultArray[i + j + 1] = sum % 10;
            resultArray[i + j] += parseInt(sum / 10);
        }
    }

    var finalResult = '';
    finalResult = resultArray.join('');
    if (finalResult[0] == 0) {
        // remove leading zero if present
        finalResult = finalResult.slice(1); 
    }
    console.log(finalResult);
}

Answer №3

function multiplyTwoNumbers(num1, num2) {
   let value1 = BigInt(num1);
   let value2 = BigInt(num2);
   let result = value1 * value2;
   return result.toString();
};

Answer №4

To efficiently perform multiplication in JavaScript, simply convert the numbers to numerical values, multiply them, and then convert the result back to a string.

function multiplyNumbers(x, y){
    return (Number(x) * Number(y)).toString();
}

In JavaScript, integers are not a distinct data type. They fall under the number type. While you could use parseInt() instead of Number() for conversion, it's unnecessary when dealing with integer inputs as we know they will be represented as whole numbers.

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

Is there a way to convert Firebase JSON into a JavaScript object? If so, what is the method to

I am currently working on using the kimono web scraper in conjunction with Firebase to obtain data stored as JSON. To convert the JSON to XML, I am utilizing a JavaScript library which allows me to create a variable from the JSON file (an example is shown ...

I'm attempting to utilize AJAX to modify the sorting and ordering arguments in a WP_Query, yet I'm struggling to pinpoint the reason behind the failure of my code

After hours of non-stop work, about 6 solid hours with no breaks, I am baffled as to why this code isn't working. Let's take a look at the form in question: <div id="wp-ajax-filter-search" class="full"> <form ...

There seems to be an issue with the syntax in ReactJS: the URL is

I'm facing an issue in my React code. I have a function that doesn't seem to be in the correct format for React. check(img) { console.log(img,typeof img) const url=""; const arrN = ["15","16","35","36","37","38","39","40" ...

When using Selenium async script in its own thread, it can interrupt the execution of other

Let's consider this situation: Various scripts need to run in the browser. One of them involves sending messages from one browser to another (WebRTC). I am interested in measuring the delay for each operation, especially when it comes to sending mess ...

Maintain selected dropdown option after page reload

I attempted to preserve the selected item after triggering a reload with an onchange event, however, I encountered this error in the console: "TypeError: o.nodeName is undefined[Learn More]" Here is my select element : <select onchange="showMov(this. ...

What is the time stamp format of 1651928421543667000?

Recently, I have encountered an issue with an API returning a timestamp as 1651928421543667000. Despite trying various PHP functions like strtotime(), datetime(), and strftime(), I am unable to find the correct format for it. Can anyone provide some guid ...

I currently have a form within a div that is part of a loop to showcase saved data. My objective is to identify any changes made in the form fields so I can detect them effectively

This code is located inside a loop <div class="card card-fluid"> @php $counterId++; $formId = 'startLog'.$counterId; @endphp {!! Form::open(['id'=>$formId,'class'=>'ajax-form','method& ...

`We enhance collaboration within sibling next components by exchanging information`

Completely new to web development, I have been working on an app with a navbar that allows users to select items from a drop-down menu. My specific issue is trying to access the title.id in a sibling component, but it keeps coming up as null. PARENT COMPO ...

What is the process for sending a POST Request to Ghostbin using Node.JS?

I'm attempting to make a POST request to Ghostbin using Node.JS and the request NPM module. Below is the code I have been utilizing: First Try: reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post" }, function (err, res, body) ...

Please provide the date using the Foundation Datepicker tool

Beginner in JavaScript here! I am having an issue with submitting dates selected using the Foundation Datepicker from . I have searched for solutions on StackOverflow like Post form on select with JQuery Datepick, but none seem to work in my case. If a Ja ...

Issue with displaying content within a custom element for children was not seen

The content within the 'Child content' span is appearing in the Light DOM, but for some reason it's not being displayed on the actual page (refer to the screenshot provided). Does anyone have any insights as to why it might not be visible? ...

Transition not influencing the scale property when activating a class

My modal is not scaling in and out properly when I toggle the 'active' class. It either fully scales out or scales in without any transition. Example: const openPopupButtons = document.querySelectorAll('[data-popup-target]'); const ...

What is the best way to locate the nearest marker using the Google Maps Direction Service?

Currently, I am engaged in the development of a Google Maps project where I am integrating markers retrieved from a database onto the map using the drawMarkers function. In addition to this, the Google Maps feature tracks your current location and refreshe ...

Swipe to modify Array

Currently, I am in the process of developing an application that features a Swipe card interface using both AngularJS and the Ionic framework. The functionality of this app will be similar to the one found at . When swiping to accept a card, I want the ar ...

"Encountering errors when attempting to load partials on the server-side

Currently, I am working on creating a basic single page application using the MEAN stack. Everything was running smoothly when I was developing on localhost. However, upon uploading the code to the server, I encountered a status code 500 (Internal Server ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

The initial value for React input is vacant and is not capturing either the state or the prop value

After utilizing Vue for an extended period, I have now transitioned to React. To practice, I am attempting to convert some basic Vue components into React. My initial Vue code was simple as shown below: <template> <div> <h1>Hello { ...

What is the method to identify the key responsible for triggering a textbox input event?

Suppose there is a textbox on the webpage: <input id='Sub' type='text'> To capture each time the input changes, you can use the following code: sub = document.getElementById('Sub'); sub.addEventListener('input&a ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Leveraging a fetch request response in componentDidMount to power a subsequent request within a React-Redux component

I am currently facing a challenge with a component that triggers a fetch request (in redux) on componentDidMount. I now need to make another fetch request in the same component using the response data from the first fetch, and ideally before rendering. Si ...