Practice · Stack · 2 of 3

Evaluate a Postfix Expression

You are given tokens, an arithmetic expression in reverse Polish (postfix) notation: each operator comes after the two values it works on. So ["4", "2", "-"] means 4 − 2, and ["1", "2", "+", "5", "*"] means (1 + 2) × 5. No brackets are ever needed.

Each token is either an integer, written in decimal (perhaps with a leading -), or one of the operators +, -, * and /. Return the value of the expression.

Division keeps only the whole-number part, rounding towards zero: 7 / 2 is 3 and −7 / 2 is −3. The expression is always valid, never divides by zero, and every value along the way fits in a 32-bit signed integer.

Example 1

Input
tokens = ["2", "3", "4", "*", "+", "10", "5", "-", "/"]
Output
2
This is (2 + 3 × 4) / (10 − 5) = 14 / 5, and 2.8 rounds towards zero to 2.

Example 2

Input
tokens = ["9", "-4", "/"]
Output
-2
9 / −4 is −2.25; rounding towards zero gives −2, not −3.

Constraints

  • tokens holds 1 to 10⁴ tokens.
  • Every number in tokens is between −200 and 200.
  • Every intermediate result is between −2³¹ and 2³¹ − 1.
Brush up firstStack visualiser