All problems

Problem 128

Evaluate Reverse Polish Notation

Medium · 20 pts · Stack, Math

Problem

Evaluate an arithmetic expression written in Reverse Polish Notation (postfix notation), where every operator comes after its two operands. For example, "3 4 +" means 3 + 4, and "2 1 + 3 *" means (2 + 1) × 3. The operators are +, -, * and /. Division between integers truncates toward zero, so 7 / -2 = -3. The expression is always valid, never divides by zero, and every intermediate value fits in a 32-bit integer. Use a stack: push numbers, and for each operator pop the two top values (the second one popped is the left operand), apply the operator and push the result.

Input

First line: integer N, the number of tokens. Second line: N tokens separated by spaces.

Output

Print the value of the expression.

Constraints

1 <= N <= 10000; operands are between -200 and 200

Example input

5
2 1 + 3 *

Example output

9

Explanation

For 2 1 + 3 *: push 2 and 1, then + pops them and pushes 3. Push 3, then * pops 3 and 3 and pushes 9. The final value is 9.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Daily Temperatures Next: Min Stack