RPN calculator · 逆波兰计算器
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.
逆波兰计算器
在逆波兰表示法中,运算符出现在它的两个数字之后:2 3 + 表示 2 + 3,而 2 3 4 * + 表示 2 + (3 * 4) = 14。不需要括号。
使用一个栈(列表)。从左到右读取记号:遇到数字就压栈;遇到运算符就弹出栈顶两个值,把它们组合起来(注意顺序 —— 先弹出的是右操作数),再把结果压栈。最后留在栈顶的就是答案。
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. · 编写 rpn_eval(tokens),计算一个逆波兰表示法的记号列表 —— 用字符串表示的整数以及运算符 +、-、*、/。使用栈;/ 向零取整。返回最终的整数。
Click Run to see the output here. · 点击“运行”查看此处输出。