← All Exercises
Reverse Polish Notation Calculator
basicjavascript
Background
Postfix notation removes parentheses entirely, which is why the HP calculator line, Forth, and PostScript all evaluate expressions with one stack.
Problem
Evaluate a token stream in reverse Polish notation. Tokens are non-negative integers or the operators + - * /. Pop two operands (second operand first), apply the operator, push the result, and at the end output the single remaining value. Division truncates toward zero.
Input
A JSON object {"tokens": string[]} forming a valid RPN expression.Output
A JSON object {"value": number} with the integer result.Sample tests
Sample 1
Input: {"tokens":["3","4","+","2","*","7","/"]}Expected: {"value":2}Sample 2
Input: {"tokens":["4","13","5","/","+"]}Expected: {"value":6}Sample 3
Input: {"tokens":["10"]}Expected: {"value":10}Your solution
Learning objective
Practice stack machines and operand ordering in postfix evaluation.