zoukankan      html  css  js  c++  java
  • 150. Evaluate Reverse Polish Notation(js)

    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.

    Note:

    • Division between two integers should truncate toward zero.
    • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

    Example 1:

    Input: ["2", "1", "+", "3", "*"]
    Output: 9
    Explanation: ((2 + 1) * 3) = 9
    

    Example 2:

    Input: ["4", "13", "5", "/", "+"]
    Output: 6
    Explanation: (4 + (13 / 5)) = 6
    

    Example 3:

    Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
    Output: 22
    Explanation: 
      ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
    = ((10 * (6 / (12 * -11))) + 17) + 5
    = ((10 * (6 / -132)) + 17) + 5
    = ((10 * 0) + 17) + 5
    = (0 + 17) + 5
    = 17 + 5
    = 22
    题意:运算一个表达式,给定一个数组,操作符紧跟数字后面
    代码如下:
    /**
     * @param {string[]} tokens
     * @return {number}
     */
    var evalRPN = function(tokens) {
        let option=[]
        if(tokens.length===1) return tokens.pop();
        for(let i=0;i<tokens.length;i++){
            let num1,num2;
            if(tokens[i]!=='+' && tokens[i]!=='-' && tokens[i]!=='*' &&   tokens[i]!=='/'){
                option.push(tokens[i]);            
            }else{
                num1=parseInt(option.pop());
                num2=parseInt(option.pop());
                switch(tokens[i]){
                    case '+':
                        option.push(num2+num1)
                        break;
                    case '-':
                        option.push(num2-num1)
                        break;
                    case '*':
                        option.push(num2*num1)
                        break;
                    case '/':
                        option.push(parseInt(num2/num1))
                        break;
                }
                
            }
        
        }
        return option.pop();
    };
  • 相关阅读:
    每日一练leetcode
    java 中 int与string的相互转化
    每日一练leetcode
    每日一题leetcode
    每日一练leetcode
    每日一练leetcode
    每日一题leetcode
    Three20在IOS6中不能正常使用 迎客
    苹果提供的支付功能接口 迎客
    ios随记 迎客
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/11186241.html
Copyright © 2011-2022 走看看