Skip to content

Commit 6689584

Browse files
author
zongyanqi
committed
add 043-Multiply-Strings
1 parent b0505f9 commit 6689584

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

043-Multiply-Strings.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* https://leetcode.com/problems/multiply-strings/description/
3+
* Difficulty:Medium
4+
*
5+
* Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
6+
* Note:
7+
* The length of both num1 and num2 is < 110.
8+
* Both num1 and num2 contains only digits 0-9.
9+
* Both num1 and num2 does not contain any leading zero.
10+
* You must not use any built-in BigInteger library or convert the inputs to integer directly.
11+
*/
12+
13+
/**
14+
* @param {string} num1
15+
* @param {string} num2
16+
* @return {string}
17+
*/
18+
var multiply = function (num1, num2) {
19+
var m = num1.length;
20+
var n = num2.length;
21+
var arr = new Array(m + n).fill(0);
22+
for (var i = m - 1; i >= 0; i--) {
23+
for (var j = n - 1; j >= 0; j--) {
24+
var mul = (num1[i] - '0') * (num2[j] - '0');
25+
26+
var sum = mul + arr[i + j + 1];
27+
28+
arr[i + j] += Math.floor(sum / 10);
29+
arr[i + j + 1] = sum % 10;
30+
}
31+
}
32+
33+
var str = arr.reduce((a, b) => {
34+
if (a === '' && b === 0) return a;
35+
return a + b;
36+
}, '');
37+
38+
return str ? str : '0';
39+
40+
};
41+
42+
console.log(multiply('89', '45'));
43+
console.log(multiply('123', '123'));
44+
console.log(multiply('123', '0'));
45+
46+

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy