华为机试-四则运算

#include<iostream>
#include<stack>
#include<string> 
using namespace std;
string op="+-*/)]}";
bool cmp(char ch1,char ch2)
{
    if(ch1=='(')
        return false;
    else if((ch1=='+'||ch1=='-')&&(ch2=='*'||ch2=='/'))
        return false;
    else
        return true;
}
void cal(stack<char> &st0,stack<int> &st)
{
    int a=st.top();st.pop();
    int b=st.top();st.pop();
    char ch=st0.top();st0.pop();
    if(ch=='+')
        a=b+a;
    if(ch=='-')
        a=b-a;
    if(ch=='*')
        a=b*a;
    if(ch=='/')
        a=b/a;
    st.push(a);
}
int main()
{
    string str;
    bool nextIsOp=false;
    while(cin>>str)
    {
        stack<char>st0;
        stack<int>st;
        str+=')';
        st0.push('('); 
        for(int i=0;i<str.size();i++)
        {
            if((str[i]=='(')||(str[i]=='[')||(str[i]=='{'))
                st0.push('(');
            else if((str[i]==')')||(str[i]==']')||(str[i]=='}'))
            {
                while(st0.top()!='(')
                    cal(st0,st);
                st0.pop();
            }
            else if(nextIsOp)
            {
                while(cmp(st0.top(),str[i]))
                    cal(st0,st);
                st0.push(str[i]);
                nextIsOp=false;
            }
            else
            {
                int j=i;
                if(str[i]=='+'||str[i]=='-')
                    i++;
                while(op.find(str[i])==op.npos)    
                    i++;
                string tmp=str.substr(j,i-j);
                st.push(stoi(tmp));
                i--;//此时i指向op,所以所以往前退一位
                nextIsOp=true;
            }
                
        }
        cout<<st.top()<<endl;
     } 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值