Skip to content

Commit 5ee55f1

Browse files
authored
Create evaluate-reverse-polish-notation.js
1 parent 57d5b31 commit 5ee55f1

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+
var evalRPN = function(tokens) {
2+
const stack = []; // ["2", "1", "+", "3", "*"]
3+
let i = 0;
4+
if(tokens.length === 1) return Number(tokens[0]);
5+
stack.push(tokens[i++]);
6+
stack.push(tokens[i++]);
7+
while(stack.length && tokens[i]) {
8+
if(!isNaN(tokens[i])) {
9+
stack.push(tokens[i]);
10+
} else {
11+
const num2 = Number(stack.pop());
12+
const num1 = Number(stack.pop());
13+
if(tokens[i] === '+') stack.push(num1 + num2);
14+
if(tokens[i] === '*') stack.push(num1 * num2);
15+
if(tokens[i] === '-') stack.push(num1 - num2);
16+
if(tokens[i] === '/') stack.push(
17+
Math.trunc(num1 / num2)
18+
);
19+
}
20+
i++;
21+
};
22+
23+
return stack.pop();
24+
};
25+
26+
//test cases
27+
[["2", "1", "+", "3", "*"], ["18"], ["4", "13", "5", "/", "+"], ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]].map(v => {
28+
console.log(evalRPN(v));
29+
});

0 commit comments

Comments
 (0)