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

Show just three items simultaneously

I am currently working on a quote generator and I want to add a feature that allows me to display a specific number of quotes at a time. I attempted to use map for this purpose, but encountered an error stating it's not a function. Currently, the gene ...

Using jQuery's .load() method is like including a file in a

Currently, Im working on revamping a company website that comes equipped with its very own CMS. Unfortunately, we are restricted from accessing the server configuration and FTP, which means I am limited to running only client-side files like HTML/CSS/J ...

Display Default Image in Vue.js/Nuxt.js when Image Not Found

I'm currently working on implementing a default image (placeholder image) for situations where the desired image resource is not found (404 error). I have a dictionary called article which contains a value under the key author_image. Although the stri ...

Dividing Faces with Lengthy Edges in three.js into Two Separate Faces

I am currently working on a script that involves splitting overly long edges of faces into two separate faces instead of one large face. The final result is exported to a .obj file. Although the geometry reduction works fine, I have noticed some issues a ...

Adding a new value to an array of objects without altering the existing values in ReactJS and NextJS

I have a JSON file containing image names that I need to organize into a Key-Value Object. I am currently using regex to create keys by removing "-img[image No]". However, I am having trouble storing all the image names in the array without overwriting pre ...

What is the best way to add data from an array to a DOM element in the same order it was retrieved from Firebase?

Utilizing Google Firebase Firestore for data storage and the Open Movie Database (OMD) in combination with Axios to retrieve movie information. I am currently developing a website that allows users to add movies to collections. On the collections page, al ...

Problem with the getJSON function

Here is a question that has been bothering me: I am currently working on a barcode scanner script which retrieves data from a JSON file. The script itself functions properly, except for one issue. After the while loop, I want to display an error alert m ...

Issues encountered while trying to integrate chessboard.js into a Vue application

I am facing an issue while trying to incorporate chessboard.js into my jetstream-vue application. Following the creation of the project, I executed the command npm install @chrisoakman/chessboardjs which successfully downloaded the package into my node_mod ...

Troubleshooting: jQuery script encountering issues with loading Bodymovin JSON files

The animations for the slider and shuffle lottie are designed to go from 0 to 100 and then back to 0 when toggled, similar to the box animation. However, it appears that the slider animation disappears in the final frame while the shuffle animation appear ...

Why do style assignments lose their motion when executed right after being made?

If you take a look at this specific fiddle in Webkit, you will see exactly what I am referring to. Is there a way to define the style of an element when it is first specified, and then its final state? I would like to be able to fully define a single-ste ...

What is the reason for the num pad being classified as a character?

Everything is functioning correctly, but when I use the number pad on the right side of my keyboard, it registers as a character and gets deleted. However, the numbers on the left side are accepted without any issue. I want to be able to input numbers usin ...

Discover the process of incorporating two distinct component structures within a single React application

In my React app, I am trying to implement a different navbar for routes that start with "admin". For example: Normal Page: <NormalNavbar/> <NormalHeader/> <NormalBody/> <NormalFooter/> But if it's an admin route, then I want: ...

I am planning to divide my web application into two sections by utilizing react router. I intend to incorporate a router within one of the routes mentioned earlier

/src |-- /components | |-- /signin | |-- SignIn.js | |-- /home | |-- Home.js | | |-- /dashboard | |-- Dashboard.js | |-- /assignee |-- /App.js |-- /index.js Dividing the project into two main parts: signi ...

Working with React, with the choice of incorporating jsx or not

I am currently delving into the world of React and found myself able to run a simple app without using JSX. In my JavaScript file, I started with: class TestClass extends React.Component Do I really need to utilize JSX or can I just stick with JavaScript ...

Tips for effectively logging data retrieved through Ajax requests

When I have content loaded via Ajax with two divs and a list, my goal is to console.log which div I was typing on when clicking on a list item. However, the issue I'm facing is that I always get the first one I clicked until I refresh the page. Altho ...

Tips for incorporating a last or recently visited feature similar to Google Docs using MongoDB

Within my database, I have two collections: users and projects. These collections share a many-to-many relationship. One user can be associated with multiple projects and one project can be assigned to multiple users. In the user object, I store an array o ...

Lamenting the Perils of Losing AngularJS Rootscope Data upon Refresh

Currently, I am facing an issue in AngularJS 1.x. When I save a value in the $rootScope and pass to the next page or router, unfortunately, the $rootScope value gets lost upon refreshing the page (F5/Window Reload). I need a solution that doesn't inv ...

Tips for enhancing undo/redo functionality when working with canvas drawings in React

Currently, I am working on implementing undo/redo functionality for html-canvas drawing on medical (.nii) images in a React application. The images consist of slices stored in a Uint8ClampedArray and usually have dimensions around 500 (cols) x 500 (rows) x ...

Display a component just once in React or React Native by utilizing local storage

I am struggling with a situation where I need to display a screen component only once using local storage. It's really frustrating. App.js ... constructor(props) { super(props); this.state = { isLoading: false, }; } component ...

Tips for resetting the form input fields in Vue.js after the user has successfully submitted the form

I am facing an issue with my registration page. After the user enters some values and successfully submits the form, I want to clear all the fields. To achieve this, I am using a predefined function called reset() inside the script section. However, the ...