我刚开始寻思着,测试样例里边这么多例子,测试样例过了应该就没问题了吧,然后提交才得了30分。。。
原来是7-9-9+8 我刚开始错误的运算顺序是先算9+8,结果15入栈,再算9-15,结果-8入栈,再算7--8,结果为15,虽然不等于24,但是很明显这样做是错的呀,竟然犯了这种小学减法加括号的错误,还好找出来了
注意这个式子 :-first+second=-(first-second) -first-second=-(first+second)
下边是一个丑丑的流程图(我也不知道为什么这么丑,但是思路应该是对的)
#include<iostream>
#include<stack>
using namespace std;
int main(){
int n;
char s[9];
stack<int> number;
stack<char> op;
scanf("%d",&n);
while(n--){
scanf("%s",&s);
while(!number.empty()){
number.pop();
}
for(int i=0;i<7;i++){
if(isdigit(s[i])){
s[i]=s[i]-'0';
if(op.empty()){
number.push(s[i]);
}
else if(op.top()=='x'){ //如果是乘号
int last=number.top();
number.pop();
int res=last*s[i];
number.push(res);
op.pop();
}
else if(op.top()=='/'){ //如果是除号
int last=number.top();
number.pop();
int res=last/s[i];
number.push(res);
op.pop();
}
else{ //如果是加号或减号
// printf("else\n");
number.push(s[i]);
}
}
else{
op.push(s[i]);
}
}
//cout<<number.top()<<endl;
while(!op.empty()){
char nowop=op.top();
op.pop();
int second=number.top();
number.pop();
int first=number.top();
number.pop();
int res=0;
char lastop;
if(!op.empty()){
lastop=op.top();
if(lastop=='-'){ //这个式子相当于 -first+second=-(first-second) -first-second=-(first+second)
if(nowop=='+'){
nowop='-';
}
else if(nowop=='-'){
nowop='+';
}
}
}
// cout<<nowop<<endl;
if(nowop=='+'){
res=first+second;
// printf("first:%d second:%d res:%d\n",first,second,res);
number.push(res);
}
else if(nowop=='-'){
res=first-second;
// printf("first:%d second:%d res:%d\n",first,second,res);
number.push(res);
}
}
if(number.top()==24){
printf("Yes\n");
}
else{
printf("No\n");
}
// printf("%d\n",number.top());
number.pop();
}
return 0;
}