Skip to content
CodeShare
All problems

Evaluate Reverse Polish Notation

Compute an arithmetic expression written in postfix order.

MediumStackMath

You're given an arithmetic expression as an array of tokens in Reverse Polish Notation, where each operator comes after its two operands: the tokens 2, 1, + mean 2 + 1.

The operators are +, -, * and /. Division between two integers truncates toward zero, and there's never a division by zero. Return the value of the expression.

Examples

Example 1
Input
tokens = ["2", "1", "+", "3", "*"]
Output
9
Why
(2 + 1) * 3 = 9.
Example 2
Input
tokens = ["4", "13", "5", "/", "+"]
Output
6
Why
4 + (13 / 5) = 4 + 2 = 6.
Example 3
Input
tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output
22

Constraints

  • 1 <= tokens.length <= 10^4
  • Each token is an operator or an integer in the range [-200, 200].
  • The expression is always valid.