deno.land / x / masx200_leetcode_test@10.6.5 / multiply-strings / index.ts

نووسراو ببینە
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import addStrings from "../add-strings/index.ts";
function multiply(x: string, y: string): string { // console.log('mul', x, y); if (x.length === 0 || y.length === 0) { throw Error("invalid empty number"); }
if ( Array.prototype.every.call(y, (s) => s === "0") || Array.prototype.every.call(x, (s) => s === "0") ) { return "0"; }
if (x === "1") { return y; }
if (y === "1") { return x; }
if (y === "2") { return addStrings(x, x); } if (x === "2") { return addStrings(y, y); }
if (x.length + y.length < 16) { return String(Number(x) * Number(y)); } if (x.length > y.length) { if (x.length >= 2) { const half = Math.floor(x.length / 2); return addStrings( multiply(y, x.slice(0, half)) + "0".repeat(x.length - half), multiply(y, x.slice(half)), ); } } else { if (y.length >= 2) { const half = Math.floor(y.length / 2); return addStrings( multiply(x, y.slice(0, half)) + "0".repeat(y.length - half), multiply(x, y.slice(half)), ); } }
throw Error("unreachable");}
export default multiply;// export default function multiply(x: string, y: string): string {// // console.log('mul', x, y);// if (x.length === 0 || y.length === 0) throw Error("invalid empty number");
// if (// Array.prototype.every.call(y, (s) => s === "0") ||// Array.prototype.every.call(x, (s) => s === "0")// ) {// return "0";// }
// if (x === "1") return y;
// if (y === "1") return x;
// if (x.length < y.length) return multiply(y, x);
// if (y === "2") return addStrings(x, x);// if (y.length >= 2) {// const half = Math.floor(y.length / 2);// return addStrings(// multiply(x, y.slice(0, half)) + "0".repeat(y.length - half),// multiply(x, y.slice(half)),// );// }// if (y === "4") return multiply("2", multiply(x, "2"));
// if (y === "8") return multiply(multiply(x, "4"), "2");
// if (["9", "7", "5", "3"].includes(y)) {// return addStrings(x, multiply(x, String(Number(y) - 1)));// }// if (y === "6") return multiply(addStrings(x, x), String(Number(y) >> 1));// throw new Error("unreachable");// }
masx200_leetcode_test

Version Info

Tagged at
a year ago