zoukankan      html  css  js  c++  java
  • 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
    

     Code:

    class Solution {
    public:
        bool isOperator(string op){
            return (op=="+"||op=="-"||op=="*"||op=="/");
        }
        
        int calculate(int operand1, int operand2, string op){
            if(op=="+")
                return operand1+operand2;
            else if(op=="-")
                return operand1-operand2;
            else if(op=="*")
                return operand1*operand2;
            else
                return operand1/operand2;
        }
        
        int evalRPN(vector<string> &tokens) {
            if(tokens.empty())
                return 0;
            stack<int> store;
            for(int i=0; i<tokens.size(); i++){
                if(isOperator(tokens[i])){
                    int operand2 = store.top();
                    store.pop();
                    int operand1 = store.top();
                    store.pop();
                    store.push(calculate(operand1, operand2, tokens[i]));
                }
                else
                    store.push(stoi(tokens[i]));
            }
            return store.top();
        }
    };
  • 相关阅读:
    LCS LIS
    补个线段树
    洛谷1522
    AC自动机
    WF 2017 I
    WF2017 E
    最小生成树计数 基尔霍夫矩阵树定理
    bitonic tour luogu1523
    code+11月月赛
    模拟退火
  • 原文地址:https://www.cnblogs.com/winscoder/p/3472337.html
Copyright © 2011-2022 走看看