-
Notifications
You must be signed in to change notification settings - Fork 0
/
1918.js
69 lines (65 loc) · 1.54 KB
/
1918.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
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
var readline = require("readline");
var r = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
r.on("line", function (line) {
input.push(line);
}).on("close", function () {
main(input);
process.exit();
});
function main(input) {
const arr = input[0].split("");
let cnt = 0;
for (letter of arr) if (letter === "(") cnt++;
while (cnt) {
let [s, e] = [-1, -1];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === "(") s = i;
else if (s !== -1 && arr[i] === ")") {
e = i;
const temp = [];
for (let j = s + 1; j < e; j++) temp.push(arr[j]);
arr[e] = calculate(temp)[0];
arr.splice(s, e - s);
cnt--;
s = -1;
e = -1;
}
}
}
console.log(calculate(arr)[0]);
}
function calculate(arr) {
let cnt = {
"+-": 0,
"*/": 0,
};
for (letter of arr) {
if (letter === "+" || letter === "-") cnt["+-"]++;
else if (letter === "*" || letter === "/") cnt["*/"]++;
}
while (cnt["*/"] || cnt["+-"]) {
for (let i = 0; i < arr.length; i++) {
const letter = arr[i];
if (cnt["*/"]) {
if (letter === "*" || letter === "/") {
arr[i + 1] = arr[i - 1] + arr[i + 1] + arr[i];
arr.splice(i - 1, 2);
cnt["*/"]--;
break;
}
} else {
if (letter === "+" || letter === "-") {
arr[i + 1] = arr[i - 1] + arr[i + 1] + arr[i];
arr.splice(i - 1, 2);
cnt["+-"]--;
break;
}
}
}
}
return arr;
}