Evaluate Reverse Polish Notation
1 approach, code in every language
Problem description
You are given a list of tokens that describe an arithmetic expression written in Reverse Polish Notation (also called postfix notation). Each token is either an integer or one of the operators +, -, *, or /.
In postfix notation an operator comes after its two operands, so there are no parentheses and the order of evaluation is fully determined by the token sequence. Evaluate the expression and return the resulting integer.
Division between two integers truncates toward zero (the fractional part is dropped), and the input is always a valid expression, so every operator will have two operands available and the result fits in a 32-bit signed integer.
Example 1
Input: tokens = ["4","13","5","/","+"]
Output: 6
This evaluates to (4 + (13 / 5)) = (4 + 2) = 6, since 13 / 5 truncates to 2.
Example 2
Input: tokens = ["2","1","+","3","*"]
Output: 9
This evaluates to ((2 + 1) * 3) = (3 * 3) = 9.
Constraints
1 <= tokens.length <= 10^4tokens[i] is either an operator (+, -, *, /) or an integer in the range [-200, 200]The given expression is always valid and never divides by zero
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Postfix Tape Total is our own problem on the technique behind Evaluate Reverse Polish Notation: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free