-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__M__basic-calculator-ii.js
77 lines (61 loc) · 1.99 KB
/
__M__basic-calculator-ii.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
70
71
72
73
74
75
76
77
// https://leetcode.com/problems/basic-calculator-ii/description/
const c = console.log.bind(console);
var calculate = function(s) {
if (s == 0) {
return 0
}
let numStack = [];
let secondStack = [];
const length = s.length;
let num = "";
for (let i = length - 1; i >= 0; i--) {
if (s[i] == "0") {
num += 0
i == 0 ? numStack.push(parseInt(num.split("").reverse().join(""))) : ''
} else {
if (parseInt(s[i])) {
num += s[i];
i == 0 ? numStack.push(parseInt(num.split("").reverse().join(""))) : "";
} else {
if (s[i] != " ") {
if (num.length > 0) {
numStack.push(parseInt(num.split("").reverse().join("")));
num = "";
}
numStack.push(parseInt(s[i]) ? parseInt(s[i]) : s[i]);
} else if (s[i] == " ") {
if (num.length > 0) {
numStack.push(parseInt(num.split("").reverse().join("")));
num = "";
}
}
}
}
}
let i = 0;
let numStackLength = numStack.length;
while (i < numStackLength) {
let popped = numStack.pop();
if (popped === "*") {
let calc = Math.floor(eval(numStack.pop() * secondStack.pop()));
secondStack.push(calc);
} else if (popped === "/") {
let calc = Math.floor(eval(secondStack.pop() / numStack.pop()));
secondStack.push(calc);
} else {
secondStack.push(popped);
}
i++;
}
return eval(secondStack.join(""));
};
// c(Math.floor(eval(0 / 3)))
// c(parseInt(q.split('').reverse().join('')))
c(calculate("5+2*3"));
// c(calculate(" 3/2 "));
c(calculate(" 3+5 / 2 "));
c(calculate("3+2*2"));
c(calculate("14/3-2")); //2
c(calculate("1*2-3/4+5*6-7*8+9/10"));
c(calculate("0"))
c(calculate("0*0"))