根据 逆波兰表示法,求表达式的值。
有效的运算符包括 +
, -
, *
, /
。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
示例 1:
输入: ["2", "1", "+", "3", "*"]输出: 9解释: ((2 + 1) * 3) = 9
示例 2:
输入: ["4", "13", "5", "/", "+"]输出: 6解释: (4 + (13 / 5)) = 6
示例 3:
输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]输出: 22解释:((10 * (6 / ((9 + 3) * -11))) + 17) + 5= ((10 * (6 / (12 * -11))) + 17) + 5= ((10 * (6 / -132)) + 17) + 5= ((10 * 0) + 17) + 5= (0 + 17) + 5= 17 + 5= 22
var evalRPN = function(tokens) {let rec = function() {let char = tokens.pop();let res;switch (char) {case '+':return rec() + rec();case '-':res = rec();return rec() - res;case '*':return rec() * rec();case '/':res = rec();return parseInt(rec() / res, 10);default:return parseInt(char, 10);}};return rec();};
var evalRPN = function() {const map = {'+': (a, b) => a + b,'-': (a, b) => a - b,'*': (a, b) => a * b,'/': (a, b) => parseInt(a / b, 10);}const rec = function () {const char = tokens.pop();if (map[char]) {let num = rec();return map[char](rec(), num);} else {return parseInt(char, 10);}}}
实现思路:
var evalRPN = function() {let stack = [];let num;for (let char of tokens) {switch (char) {case '+':stack.push(stack.pop() + stack.pop());break;case '-':num = stack.pop();stack.push(stack.pop() - num);break;case '*':stack.push(stack.pop() * stack.pop());break;case '/':num = stack.pop();stack.push(parseInt(stack.pop() / num, 10));break;default:stack.push(parseInt(char, 10));}}return stack.pop();};