Skip to content

Commit fee7432

Browse files
committed
150 / Evaluate Reverse Polish Notation / Medium / 36m 44s
1 parent 4f08293 commit fee7432

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
*
3+
* 150 / Evaluate Reverse Polish Notation / Medium / 36m 44s
4+
*
5+
* @param {string[]} tokens
6+
* @return {number}
7+
*/
8+
var evalRPN = function (tokens) {
9+
const operators = {
10+
"+": (a, b) => a + b,
11+
"-": (a, b) => a - b,
12+
"*": (a, b) => a * b,
13+
"/": (a, b) => Math.trunc(a / b),
14+
};
15+
16+
const stack = [];
17+
18+
for (const token of tokens) {
19+
if (operators?.[token]) {
20+
const b = stack.pop();
21+
const a = stack.pop();
22+
stack.push(operators[token](a, b));
23+
} else {
24+
stack.push(+token);
25+
}
26+
}
27+
28+
return stack.pop();
29+
};

0 commit comments

Comments
 (0)