150. Evaluate Reverse Polish Notation

来源:互联网 发布:mac如何合上盖子不休眠 编辑:程序博客网 时间:2024/06/08 06:43
//16ms acclass Solution {public:    int atoi(string s)    {        int i=0,l=1,r=0;        bool flag=false;        if(s[0]=='-')        {            r=1;            flag=true;        }        for(int j=s.size()-1;j>=r;j--)        {            i+=(s[j]-'0')*l;            l*=10;        }        if(flag) return 0-i;        return i;    }    int evalRPN(vector<string>& tokens) {        stack<int> s;        s.push(atoi(tokens[0]));        int i=1;        while(i<=tokens.size()-1)        {            if(tokens[i]=="+")            {                int a=s.top();                s.pop();                int b=s.top();                s.pop();                s.push(a+b);            }            else if(tokens[i]=="-")            {                int a=s.top();                s.pop();                int b=s.top();                s.pop();                s.push(b-a);            }            else if(tokens[i]=="*")            {                int a=s.top();                s.pop();                int b=s.top();                s.pop();                s.push(b*a);            }            else if(tokens[i]=="/")            {                int a=s.top();                s.pop();                int b=s.top();                s.pop();                s.push(b/a);            }            else s.push(atoi(tokens[i]));            i++;        }        return s.top();    }};
0 0