RPN calculator
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
RPN calculator
In Reverse Polish Notation the operator comes after its two numbers: 2 3 + means 2 + 3, and 2 3 4 * + means 2 + (3 * 4) = 14. No brackets needed.
Use a stack (a list). Read tokens left to right: push numbers; when you hit an operator, pop the top two, combine them (mind the order — the first value popped is the right-hand side), and push the result. The answer is what's left on top.
Write rpn_eval(tokens) that evaluates a list of Reverse Polish Notation tokens — integers written as strings and the operators +, -, *, /. Use a stack; / should truncate toward zero. Return the final integer.
Click Run to see the output here.