-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
34 lines (32 loc) · 995 Bytes
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// note:
// a and b are whole, positive numbers as strings
// examples:
// multiply("52", "100"); - returns "5200"
// multiply("358534858986", "858585883946"); - returns "307832968827949271238756"
function multiply(a, b) {
var product = [...new Array(a.length + b.length)];
for (var k = 0; k < product.length; k++) {
product[k] = 0;
}
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
product[product.length - 1 - i - j] +=
parseInt(a[a.length - 1 - i]) * parseInt(b[b.length - 1 - j]);
}
}
for (var l = product.length - 1; l > -1; l--) {
if (product[l].toString().length > 1) {
product[l - 1] += parseInt(
product[l].toString().slice(0, product[l].toString().length - 1)
);
product[l] = product[l].toString();
product[l] = product[l][product[l].length - 1];
}
}
product = product.join("");
if (product == 0) {
return "0";
} else {
return product.replace(/\b0+/g, "");
}
}