首页 > 编程语言 > 详细

[LeetCode][JavaScript]Evaluate Reverse Polish Notation

时间:2015-07-04 00:43:15      阅读:253      评论:0      收藏:0      [点我收藏+]

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 };

 

 

[LeetCode][JavaScript]Evaluate Reverse Polish Notation

原文:http://www.cnblogs.com/Liok3187/p/4619981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!