Weekly Algorithm Question---Reverse Polish notation, find the calculation result of the suffix expression

Evaluates the suffix expression according to reverse Polish notation.

Valid operators include +, -, *, /. Each operand can be an integer or another reverse Polish expression.

illustrate:

Integer division keeps only the integer part.
The given reverse Polish expression is always valid. In other words, the expression will always result in a valid value and there will be no division by zero.

problem solving ideas

Write problem-solving ideas here

The stack structure is used, if it is not an operator, it will be pushed onto the stack, if it is an operator, the first two values ​​in the stack will be popped for calculation, you need to pay attention to the order of popping the stack, the division is the divisor first, the eval method is wrapped with (), and finally The result of the operation is also pushed onto the stack

/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function(tokens) {
   let stack = []
    let pie = ['-', '+', '*', '/']
    while (tokens.length) {
        let item = tokens.shift()
        if (pie.includes(item)) {
            // 弹出两个数
            let num1 = stack.pop()
            let num2 = stack.pop()
            let resulet = parseInt(eval('(' + num2 + ')' + item + '(' + num1 + ')'))
//将运算结果入栈
            stack.push(resulet)
        } else {//入栈
            stack.push(item)
        }
    }
    return stack[0]
};

 

 

Guess you like

Origin blog.csdn.net/qq_27449993/article/details/128930573