其他分享
首页 > 其他分享> > 表达式求值

表达式求值

作者:互联网

https://www.acwing.com/problem/content/3305/

#include<iostream>
#include<cstring>
#include<stack>
#include<unordered_map>
#include<string>
#include<algorithm>
using namespace std;
stack<int> num;
stack<char> op;

unordered_map<char,int> mp={{'+',1},{'-',1},{'*',2},{'/',2}};

void evel()
{
    int a=num.top();
    num.pop();
    int b=num.top();
    num.pop();
    char c=op.top();
    op.pop();
    int r=0;
    if(c=='+') r=b+a;
    if(c=='-') r=b-a;
    if(c=='*') r=b*a;
    if(c=='/') r=b/a;
    num.push(r);
}

int main()
{
    string s;
    cin>>s;
    for(int i=0;i<s.size();i++)
    {
        if(isdigit(s[i]))
        {
            int x=0,j=i;
            while(j<s.size()&&isdigit(s[j]))
            {
                x=x*10+s[j]-'0';
                j++;
            }
            i=j-1;
            num.push(x);
        }
        else if(s[i]=='(')
        {
            op.push(s[i]);
        }
        else if(s[i]==')')
        {
            while(op.top()!='(')
            {
                evel();
            }
            op.pop();
        }
        else
        {
            while(op.size()&&mp[op.top()]>=mp[s[i]])
            {
                evel();
            }
            op.push(s[i]);   
        }
    }
    while(op.size())
    {
        evel();
    }
    cout<<num.top()<<endl;
    return 0;
}

标签:evel,int,pop,num,求值,include,表达式,op
来源: https://www.cnblogs.com/xjtfate/p/16638569.html