All problems
0146MediumArrayMathStack

Postfix Tape Total

Tracked in this browser only
Write code

Trains the technique from

LeetCode 150Evaluate Reverse Polish Notation

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A machinist's paper-tape calculator writes its keystrokes in postfix order: values are typed first, and an operator key is pressed only once both values it will work on already sit on the tape. The finished tape arrives as tokens, one keystroke per entry. An entry is either a whole number in decimal, possibly carrying a minus sign, or one of the four keys "+", "-", "*", "/".

Replay the tape and report the single value that remains when the last keystroke has been handled.

  • An operator key takes the two most recently produced values. The one produced earlier is its left operand.
  • The divide key drops the fractional part and pulls the quotient toward zero, so a quotient of -3.7 lands on -3.
  • Every tape you are given is well formed: each operator key finds two values waiting, no divide key ever meets a zero on its right, and every value produced along the way fits in a signed 32-bit register.

Examples

Example 1

Input
tokens = ["5", "2", "-"]
Output
3

The minus key takes 5 as its left operand and 2 as its right, leaving 3 on the tape.

Example 2

Input
tokens = ["-7", "2", "/"]
Output
-3

A true quotient of -3.5 is pulled toward zero, so the tape keeps -3 rather than -4.

Example 3

Input
tokens = ["8", "3", "+", "2", "*", "5", "-"]
Output
17

The tape builds 11, doubles it to 22, then subtracts 5.

Constraints

  • 1 <= tokens.length <= 10^4
  • Each entry of tokens is one of "+", "-", "*", "/", or a whole number from -200 through 200.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def eval_r_p_n(tokens: list[str]) -> int:
Java
public int evalRPN(String[] tokens)
September 7
Apply