Problem 223865 · easy · Level 02 Linear Data Structures

Replay the Calculator Tape

stacks · parsing

In Reverse Polish Notation (postfix), the operator comes after its two operands: 4 2 - means 4 - 2, and 4 2 - 5 * means (4 - 2) * 5. 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.

An old desk calculator works in RPN and prints every key press on a paper tape: each entry is a whole number or one of +, -, * and /. Given the tape as a list of strings tokens, which always holds a valid expression, return the integer the calculator shows at the end. Its division keeps only the whole-number part, cutting toward zero (so 7 / -2 gives -3, not -4), and it is never asked to divide by zero.

Examples

Input:  tokens = ["4", "2", "-", "5", "*"]
Output: 10
Explanation: (4 - 2) * 5 = 10
Input:  tokens = ["3", "17", "4", "/", "+"]
Output: 7
Explanation: 3 + (17 / 4) = 3 + 4 = 7

Constraints

  • 1 <= len(tokens) <= 10**4
  • Every token is an operator or an integer in the range -200 <= x <= 200
  • Every intermediate result fits in a 32-bit signed integer
  • 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…