Overview
Evaluate the value of an arithmetic expression in Reverse Polish Notation (postfix). Valid operators are +, -, *, /. Division truncates toward zero.
Constraints
1 <= tokens.length <= 10,000- Each token is an operator or an integer in the range
[-200, 200]. - The expression is always valid.
Examples
evalRPN(["2","1","+","3","*"]); // => 9 ((2+1)*3) evalRPN(["4","13","5","/","+"]); // => 6 (4+(13/5))
Solution
Reveal solution
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(parseInt(t));
}
}
return stack[0];
}Resources
evaluate-reverse-polish-notation.js
Evaluate Reverse Polish Notation
mediumcodingAlgorithmsStacks
Overview
Evaluate the value of an arithmetic expression in Reverse Polish Notation (postfix). Valid operators are +, -, *, /. Division truncates toward zero.
Constraints
1 <= tokens.length <= 10,000- Each token is an operator or an integer in the range
[-200, 200]. - The expression is always valid.
Examples
evalRPN(["2","1","+","3","*"]); // => 9 ((2+1)*3) evalRPN(["4","13","5","/","+"]); // => 6 (4+(13/5))
Solution
Reveal solution
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(parseInt(t));
}
}
return stack[0];
}Resources
NameTopicDifficulty
103 of 103 problems