zoukankan      html  css  js  c++  java
  • LeetCode-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
    
    遇到数字入栈,遇到运算符将前两个数字出栈,并将结果入栈
    
    class Solution {
    public:
        bool checkDigit(string str,int& value){
            bool ret=true;
            int v=0;
            int i=0;
            bool neg=false;
            if(str[0]=='-'){
                i++;
                if(str.size()==1)return false;
                neg=true;
            }
            for(;i<str.length();i++){
                if(str[i]>='0'&&str[i]<='9'){
                    v*=10;
                    v+=str[i]-'0';
                }
                else return false;
            }
            if(neg)value=-v;
            else value=v;
            return ret;
        }
        int evalRPN(vector<string> &tokens) {
            stack<int> sta;
            int value;
            for(int i=0;i<tokens.size();i++){
                if(checkDigit(tokens[i],value)){
                    sta.push(value);
                    //cout<<"push"<<value<<endl;
                }
                else{
                    int v2=sta.top();
                    sta.pop();
                    int v1=sta.top();
                    sta.pop();
                    if(tokens[i]=="+"){
                        sta.push(v1+v2);
                        //cout<<v1<<"+"<<v2<<"="<<v1+v2<<endl;
                    }
                    else if(tokens[i]=="-"){
                        sta.push(v1-v2);
                        //cout<<v1<<"-"<<v2<<"="<<v1-v2<<endl;
                    }
                    else if(tokens[i]=="*"){
                        sta.push(v1*v2);
                        //cout<<v1<<"*"<<v2<<"="<<v1*v2<<endl;
                    }
                    else{
                        sta.push(v1/v2);
                        //cout<<v1<<"/"<<v2<<"="<<v1/v2<<endl;
                    }
                }
            }
            return sta.top();
        }
    };
    View Code
  • 相关阅读:
    hdu 1018
    hdu 1005
    hdu 1222
    hdu 1297
    hdu 1568
    WCF入门, 到创建一个简单的WCF应用程序
    BarTender 通过ZPL命令操作打印机打印条码, 操作RFID标签
    WCF入门的了解准备工作
    C# Bartender模板打印 条码,二维码, 文字, 及操作RFID标签等。
    Qt configure脚本说明
  • 原文地址:https://www.cnblogs.com/superzrx/p/3462029.html
Copyright © 2011-2022 走看看