[LeetCode][JavaScript]Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

https://leetcode.com/problems/evaluate-reverse-polish-notation/


逆波兰表达式,也就是后缀表达式,做过两道更难的题之后,这题秒了。

http://www.cnblogs.com/Liok3187/p/4564877.html

http://www.cnblogs.com/Liok3187/p/4593365.html

 1 /**
 2  * @param {string[]} tokens
 3  * @return {number}
 4  */
 5 var evalRPN = function(tokens) {
 6     var resStack = [];
 7     var opStack = [];
 8     var right, left;
 9     for(var i  = 0; i < tokens.length; i++){
10         var curr = tokens[i];
11         if(/^(+|-|/|*)$/.test(curr)){
12             right = resStack.pop();
13             left = resStack.pop();
14             if(curr === '+'){
15                 resStack.push(left + right);
16             }else if(curr === '-'){
17                 resStack.push(left - right);
18             }else if(curr === '/'){
19                 resStack.push(parseInt(left / right));
20             }else if(curr === '*'){
21                 resStack.push(left * right);
22             }
23         }else{
24             resStack.push(parseInt(curr));    
25         }
26     }
27     return resStack[0];
28 };
原文地址:https://www.cnblogs.com/Liok3187/p/4619981.html