#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;
}
}
华为机试-四则运算
最新推荐文章于 2024-05-06 07:35:18 发布