Postfix Calculator

EasyStack≈ 20 min

In postfix notation every operator comes after the two values it joins: 3 4 + means 3 + 4, and 3 4 + 2 * means (3 + 4) × 2. No brackets are ever needed.

You are given the expression as a list of tokens, each either an integer or one of +, -, *, /. Return the value of the expression.

  • Division keeps the whole part and drops the fraction, rounding toward zero: 7 / -2 is -3, and -7 / 2 is -3 too.
  • The expression is always valid, never divides by zero, and every value along the way stays between -1,000,000,000,000 and 1,000,000,000,000.

Examples

text
tokens = ["3", "4", "+", "2", "*"]                       →  14
tokens = ["5", "1", "2", "+", "4", "*", "+", "3", "-"]   →  14
tokens = ["7"]                                           →  7
tokens = ["7", "-2", "/"]                                →  -3

The second example is 5 + (1 + 2) × 4 − 3.

Constraints

  • Between 1 and 20,001 tokens; each number is between -1,000 and 1,000.
  • Aim for O(n): handle each token once.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.