思路:表达式求值问题。遇到数字,加入数字栈中;遇到+,将加数加入到栈中;遇到-,将减数的相反数加入栈中;遇到x,让栈顶的数字出栈,与乘数相乘,将结果加入栈中;遇到/,让栈顶的数字出栈,与除数相除,将结果加入栈中;最后将栈中所有元素相加即可。
注意:输入的表达式存储在string中,故要的到数字应用str[i]-'0'。
代码实现:
#include<iostream>
#include<string>
#include<stack>
using namespace std;
stack<int> s;
int main(){
int n;
cin>>n;
string str;
for(int i = 0; i < n; i++){
cin>>str;
for(int j = 0; j < str.size();j++){
if(str[j] > '0' && str[j] <= '9'){
s.push(str[j]-'0');
}
else if(str[j] == '+'){
s.push(str[++j]-'0');
}
else if(str[j] == '-'){
s.push('0' - str[++j]);
}
else if(str[j] == 'x'){
int tmp = s.top();
s.pop();
s.push(tmp*(str[++j]-'0'));
}
else if(str[j] == '/'){
int tmp = s.top();
s.pop();
s.push(tmp/(str[++j]-'0'));
}
}
int sum = 0;
while(!s.empty()){
sum += s.top();
s.pop();
}
// cout<<sum<<endl;
if(sum == 24){
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}
}
return 0;
}