Skip to content

Commit e5fca2b

Browse files
committed
Add solution #43
1 parent 8c060e3 commit e5fca2b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
|:---|:---|:---|
99
4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard|
1010
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
11+
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|
1112
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
1213
67|[Add Binary](./0067-add-binary.js)|Easy|
1314
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|

solutions/0043-multiply-strings.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 43. Multiply Strings
3+
* https://leetcode.com/problems/multiply-strings/
4+
* Difficulty: Medium
5+
*
6+
* Given two non-negative integers num1 and num2 represented as strings,
7+
* return the product of num1 and num2, also represented as a string.
8+
*
9+
* - The length of both num1 and num2 is < 110.
10+
* - Both num1 and num2 contain only digits 0-9.
11+
* - Both num1 and num2 do not contain any leading zero, except the number 0 itself.
12+
* - You must not use any built-in BigInteger library or convert the inputs to integer directly.
13+
*/
14+
15+
/**
16+
* @param {string} num1
17+
* @param {string} num2
18+
* @return {string}
19+
*/
20+
var multiply = function(num1, num2) {
21+
const result = new Array(num1.length + num2.length).fill(0);
22+
for (let i = num1.length - 1; i >= 0; i--) {
23+
for (let j = num2.length - 1; j >= 0; j--) {
24+
const sum = num1[i] * num2[j] + result[i + j + 1];
25+
result[i + j] += Math.floor(sum / 10);
26+
result[i + j + 1] = sum % 10;
27+
}
28+
}
29+
return result.join('').replace(/^0+(?!$)/, '');
30+
};
31+
32+
// one-liner alternative that breaks the rules:
33+
/**
34+
* @param {string} num1
35+
* @param {string} num2
36+
* @return {string}
37+
*/
38+
var multiply = function(num1, num2) {
39+
return ((BigInt(num1) * BigInt(num2))).toString();
40+
};

0 commit comments

Comments
 (0)