150. Evaluate Reverse Polish Notation

Posted bubbleStar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了150. 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

解题思路:

用栈来做,如果是数字则push进去,如果遇到运算符则将栈顶的两个数字push出,运算完成后再push进栈。

我的javascript代码:

var evalRPN = function(tokens) {
    var arr = []; var num;
    for(let i = 0; i < tokens.length; i++){
        if( !isNaN(tokens[i]) ){
            arr.push(tokens[i]);
        }else{
            let a = arr.pop(),b = arr.pop();
            a = parseInt(a); b = parseInt(b);
            if( tokens[i] === ‘+‘ ){
                num = b+a;
            }else if( tokens[i] === ‘-‘ ){
                num = b-a;
            }else if( tokens[i] === ‘*‘ ){
                num = b*a;
            }else if( tokens[i] === ‘/‘ ){
                if( (a*b)<0 ) num = Math.ceil( b/a );
                else num = Math.floor( b/a );
            }
            arr.push( num );
        }
    }
    return parseInt( arr[0] );
};

 

参考了https://discuss.leetcode.com/topic/18179/accepted-clean-java-solution之后,使用swith-case,更加干净的代码:

/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function(tokens) {
    var stack = [];
    for (var i = 0; i < tokens.length; i++) {
    switch (tokens[i]) {
      case "+":
        stack.push(stack.pop() + stack.pop());
        break;
          
      case "-":
        stack.push(-stack.pop() + stack.pop());
        break;
          
      case "*":
        stack.push(stack.pop() * stack.pop());
        break;

      case "/":
        var n1 = stack.pop(), n2 = stack.pop();
        if( n1*n2 > 0) stack.push( Math.floor(n2 / n1) );
        else stack.push( Math.ceil( n2 / n1) );
        break;
          
      default:
        stack.push( parseInt(tokens[i]) );
    }
  }
  
  return stack.pop();
};

总结与注意:

1. 判断字符串为数字的方法:isNaN( str );

2. 除法与减法操作时,数字的先后位置需要注意;

3. JavaScript中,整除的操作需要分为两类:

  • 两个数同号,整除结果Math.floor( a/b )
  • 两个数异号,整除结果Math.ceil( a/b )

以上是关于150. Evaluate Reverse Polish Notation的主要内容,如果未能解决你的问题,请参考以下文章

150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation

leetcode150 Evaluate Reverse Polish Notation

[leetcode-150-Evaluate Reverse Polish Notation]

刷题-LeetCode150 Evaluate Reverse Polish Notation

[LeetCode] 150. Evaluate Reverse Polish Notation