-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval-rpn.js
More file actions
59 lines (54 loc) · 1.11 KB
/
eval-rpn.js
File metadata and controls
59 lines (54 loc) · 1.11 KB
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
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function (tokens) {
const stack = [];
let leftSideOperand = null;
let rightSideOperand = null;
for (const token of tokens) {
if (!isNaN(token)) {
stack.push(Number.parseInt(token, 10));
} else {
rightSideOperand = stack.pop();
leftSideOperand = stack.pop();
switch (token) {
case "+":
stack.push(leftSideOperand + rightSideOperand);
break;
case "-":
stack.push(leftSideOperand - rightSideOperand);
break;
case "*":
stack.push(leftSideOperand * rightSideOperand);
break;
case "/":
const divisionOutput = leftSideOperand / rightSideOperand;
if (divisionOutput > 0) {
stack.push(Math.floor(divisionOutput));
} else {
stack.push(Math.ceil(divisionOutput));
}
break;
}
}
}
return stack.pop();
};
console.log(
evalRPN([
"10",
"6",
"9",
"3",
"+",
"-11",
"*",
"/",
"*",
"17",
"+",
"5",
"+",
]),
);