讨论/《队列 & 栈》 - 逆波兰表达式求值/
《队列 & 栈》 - 逆波兰表达式求值

JavaScript解法

js的解法,唯一需要注意的是js里的除法4取商是会四舍五入的,在经过parseInt 字符转换数字之后,还需要再进行一次parseInt

var evalRPN = function(tokens) {
    let stacks = [];
    for (let i = 0; i < tokens.length; i++) {
        if (tokens[i] == '+') {
            let a = stacks.pop();
            let b = stacks.pop();
            stacks.push(b + a);
        } else if (tokens[i] == '-') {
            let a = stacks.pop();
            let b = stacks.pop();
            stacks.push(b - a);
        } else if (tokens[i] == '*') {
            let a = stacks.pop();
            let b = stacks.pop();
            stacks.push(b * a);
        } else if (tokens[i] == '/') {
            let a = stacks.pop();
            let b = stacks.pop();
            stacks.push(parseInt(b / a)); // 无需四舍五入,直接取整。
        } else {
            stacks.push(parseInt(tokens[i]));
        }
    }

    return stacks.pop();
}
展开全部 10 讨论