Calculator Tape
Easy · Stack & Monotonic Stack · about 15 min
An old shop calculator prints its work on a paper tape in postfix order: the two numbers come first and then the operator. For example 3 4 + means 3 + 4, and 3 4 + 2 * means (3 + 4) * 2.
You get the tape as a list of tokens. Each token is an integer (it may be negative, like "-7") or one of "+", "-", "*", "/". An operator uses the two most recent results: the older one is on the left. Division cuts toward zero (7 / -2 is -3, and -7 / 2 is -3). The tape is always valid and never divides by zero.
Return the final value.
Example: calculator_tape(["3", "4", "+", "2", "*"]) → 14
Example: calculator_tape(["10", "3", "-"]) → 7
Constraints: 1 to 10,000 tokens; every intermediate value fits in a 32-bit signed integer.
Hints
- Every operator needs the two most recent values. Which structure gives you the most recent value first?
- Pop twice: the first pop is the right operand, the second is the left one.
- For division, divide the sizes and then fix the sign, so the result moves toward zero. Check whole tokens: "-7" is a number.
Learn the pattern first: the Stack & Monotonic Stack lesson.
More Stack & Monotonic Stack problems
- Config Bracket Check (Easy)
- Cancelling Beads (Easy)
- Lightest Parcel on the Pile (Medium)
- Banner Expander (Medium)
- Taller Friend at the Round Table (Medium)
- Scooter Convoys (Medium)
- Biggest Skyline Billboard (Hard)