题解 | #四则运算#
四则运算
http://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
#include <bits/stdc++.h>
using namespace std;
//创建两个栈,一个操作数栈一个符号栈
const int maxn=1e3+5;
int num[maxn];
char operation[maxn];
int cnt1,cnt2;//两个指针
//判断当前输入的算符和栈顶算符优先级函数//栈顶优先级低,入栈,否则计算
int YouXian(char c){
char top=operation[cnt2];
if(top=='*'||top=='/'){
if(c=='+'||c=='-'||c=='*'||c=='/'||c==')'||c==']'||c=='}'||c=='#')
return 1;//计算
return -1;//(,[,{
}
else if(top=='+'||top=='-'){
if(c=='+'||c=='-'||c==')'||c==']'||c=='}'||c=='#')
return 1;
return -1;
}
else if(top=='{'){
if(c=='}')
return 0;
return -1;
}
else if(top=='['){
if(c==']')
return 0;
return -1;
}
else if(top=='('){
if(c==')')
return 0;
return -1;
}
else if(top=='}'||top==']'||top==')')
return 1;
else{//#
if(c=='#')
return 0;
return -1;
}
}
int main(){
string s;
int ans=0;
while(cin>>s){
s=s+"#";//添加判断符号
operation[++cnt2]='#';
char cur='?';
for(int i=0;i<s.length();i++){
if(operation[cnt2]=='#'&&s[i]=='#')
break;
int j=i;
if((s[i]=='('||s[i]=='['||s[i]=='{') && i<s.length() - 1 && s[i + 1] == '-')
num[++cnt1]=0;
while(isdigit(s[i])) i++;
if(j!=i) num[++cnt1]=stoi(s.substr(j,i-j));
cur=s[i];
int ans2=YouXian(cur);
if(ans2==-1){
operation[++cnt2]=cur;continue;
}
else if(ans2==0){
cnt2--;continue;
}
else{
int b=num[cnt1],a=num[--cnt1];
char top=operation[cnt2];
cnt2--;i--;
num[cnt1]=top=='*'?a*b:top=='/'?a/b:top=='+'?a+b:a-b;
}
}
cout<<num[1]<<endl;
}
}