← Back to puzzles

001 RPN Calculator

Reverse Polish Notation (RPN) is a stack-based way to evaluate mathematical expressions, where the user inputs a series of numbers and operators. Numbers are pushed onto a stack. When an operator appears (i.e. +, -, * or /), the calculator pops the top two numbers, applies the operation, and pushes the result back on the stack. The final number on the stack is the answer.

Example: Given the expression "4 3 -", we should first push 4 onto the stack, then 3. When we get the "-", we pop the numbers off the stack and subtract them, giving 1.

Your assignment is to write an "rpn" function that, given a string containing an expression, returns the result of the expression as a number.

Here are some example inputs and expected outputs:

"4 2 /" → 2
"7 2 3 * -" → 1
"2 3 11 + 5 - *" → 18

You can assume that the user only inputs correct programs, and that the calculator only needs to handle integers.