Problem 223865 · easy · Phase 02 Linear Data Structures

Evaluate Reverse Polish Notation

stacks · parsing

In Reverse Polish Notation (postfix), the operator comes after its two operands: 2 1 + means 2 + 1, and 2 1 + 3 * means (2 + 1) * 3. No parentheses are needed, and a stack evaluates it naturally: push numbers, and when an operator appears, pop two numbers, apply it, and push the result.

Given a list of string tokens tokens representing a valid RPN expression, return its integer value. The operators are +, -, * and /. Division between two integers truncates toward zero (so 7 / -2 is -3, not -4), and the divisor is never zero.

Examples

Input:  tokens = ["2", "1", "+", "3", "*"]
Output: 9
Explanation: (2 + 1) * 3 = 9
Input:  tokens = ["4", "13", "5", "/", "+"]
Output: 6
Explanation: 4 + (13 / 5) = 4 + 2 = 6

Constraints

  • 1 <= len(tokens) <= 10**4
  • Every token is an operator or an integer in the range -200 <= x <= 200
  • The expression is always valid

Goals

  • Use a stack to evaluate postfix expressions
  • Pop operands in the correct order for non-commutative operators
  • Implement integer division that truncates toward zero
Starting Python…