Evaluate Reverse Polish Notation
You're given an arithmetic expression written in Reverse Polish (postfix) Notation as a list of tokens. Compute its value, where the supported operators are +, -, *, and /, and division between two integers truncates toward zero rather than rounding down.
Input Format
Implement evalRPN(tokens). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
tokens = ["2","1","+","3","*"] Output
9 Example 2
Input
tokens = ["4","13","5","/","+"] Output
6 Constraints
- 1 <= tokens.length <= 10^4
- tokens[i] is an operator or integer in [-200, 200]
Test Cases (2)
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.