Evaluate Reverse Polish Notation
Evaluate an expression in Reverse Polish Notation. Valid operators are +, -, *, /. Division truncates toward zero.
Example: tokens = ["2","1","+","3","*"] → Output: 9 ((2+1)*3)
Sample Input
—
Sample Output
—
Constraints
- 1 <= tokens.length <= 10^4
- tokens[i] is an operator or integer in [-200, 200]
Test Cases
Case 1
Args: [["2","1","+","3","*"]]
Expected: 9
Case 2
Args: [["4","13","5","/","+"]]
Expected: 6
Topics
Stack
function evalRPN(tokens) {
const stack = [];
for (const t of tokens) {
if ('+-*/'.includes(t)) {
const b = stack.pop(), a = stack.pop();
if (t === '+') stack.push(a + b);
else if (t === '-') stack.push(a - b);
else if (t === '*') stack.push(a * b);
else stack.push(Math.trunc(a / b));
} else stack.push(Number(t));
}
return stack[0];
}
Time: O(n) | Space: O(n)
Saved in this browser only. Private to you.