Evaluate an arithmetic expression in Reverse Polish Notation. Operators are +, −, *, /; division truncates toward zero.
Push numbers. On an operator, pop the right then the left operand, apply it, and push the result. The last value on the stack is the answer.
1function evalRPN(tokens: string[]): number {2const stack: number[] = [];3for (const tok of tokens) {4if (!["+", "-", "*", "/"].includes(tok)) { stack.push(+tok); continue; }5const b = stack.pop()!, a = stack.pop()!;6stack.push(tok === "+" ? a + b : tok === "-" ? a - b : tok === "*" ? a * b : Math.trunc(a / b));7}8return stack[0];9}
Empty stack.
Space: play/pause · ←/→: step