-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathp150-expression.js
37 lines (37 loc) · 1.11 KB
/
p150-expression.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
//https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/submissions/
var evalRPN = function(tokens) {
let stack = [];
for (let i = 0; i < tokens.length; i++) {
if (
tokens[i] === "+" ||
tokens[i] === "-" ||
tokens[i] === "*" ||
tokens[i] === "/"
) {
let a = stack.pop();
let b = stack.pop();
if (tokens[i] === "+") {
stack.push(a + b);
}
if (tokens[i] === "-") {
stack.push(b - a);
}
if (tokens[i] === "*") {
stack.push(a * b);
}
if (tokens[i] === "/") {
let ret = b / a;
if (ret < 0) {
ret = -1 * Math.floor(Math.abs(ret));
} else {
ret = Math.floor(ret);
}
stack.push(ret);
}
} else {
stack.push(parseInt(tokens[i]));
}
}
return stack.pop();
};
evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]);