用两个栈,一个存放符号,一个存放数值。
依次读取符号,如果是乘除,数值栈顶端数出栈,与符号后面的数进行运算,结果放入数值栈。如果符号是加和减,如果符号栈不为空,先运算符号栈和数值栈,把结果放入数值栈,再把符号放入符号栈,符号后面的数放入数值栈。
#include<iostream>
#include<stack>
using namespace std;
int main(int argc, char** argv) {
int n;
cin>>n;
for(int j=0;j<n;j++){
string str;
cin>>str;
stack<char> fuhao; //符号栈
stack<int> jieguo; //数值栈
jieguo.push((int)str[0]-48);
int i=1;
while(i<7){
if(str[i]=='x'||str[i]=='/'){
int a=jieguo.top();
jieguo.pop();
if(str[i]=='x'){
jieguo.push(a*((int)str[i+1]-48));
}else{
jieguo.push(a/((int)str[i+1]-48));
}
}else{
if(!fuhao.empty()){
int q1=jieguo.top();
jieguo.pop();
int q2=jieguo.top();
jieguo.pop();
if(fuhao.top()=='+'){
jieguo.push(q1+q2);
}else{
jieguo.push(q2-q1);
}
fuhao.pop();
}
jieguo.push((int)str[i+1]-48);
fuhao.push(str[i]);
}
i+=2;
}
if(!fuhao.empty()){
int q1=jieguo.top();
jieguo.pop();
int q2=jieguo.top();
jieguo.pop();
if(fuhao.top()=='+'){
jieguo.push(q1+q2);
}else{
jieguo.push(q2-q1);
}
fuhao.pop();
}
if(jieguo.top()==24){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}
return 0;
}