Evaluate Reverse Polish Notation
In reverse Polish notation an operator comes after its two operands: 3 4 + is 3 + 4, and 5 1 2 + 4 * + 3 - is 5 + ((1 + 2) × 4) - 3.
tokens is a valid expression, one token per element: an integer, or one of +, -, *, /. Return its value. Division between integers truncates toward zero (7 / -2 is -3), and there is no division by zero.
Constraints
- 1 ≤ length of
tokens≤ 10,000 - Every number, and every intermediate result, fits in a 32-bit integer.
Example 1
Input
tokens = ["2","1","+","3","*"]
Output
9
Why:
(2 + 1) × 3.
Example 2
Input
tokens = ["4","13","5","/","+"]
Output
6
Why:
13 / 5 truncates to 2, and 4 + 2 = 6.
Example 3
Input
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output
22
Why:
6 / (12 × -11) truncates to 0, so it's 10 × 0 + 17 + 5.
Hints
Was this a good challenge?
- Solved by
- 1
- Submissions
- 1
- Accepted
- 100%