#include <iostream>
#include <stack>
using namespace std;
int calculate(int num1, int num2, char op){
switch(op){
case '+':
return num1+num2;
case '-':
return num1-num2;
case 'x':
return num1*num2;
case '/':
return num1/num2;
}
}
int main(){
int n;
cin >> n;
int i = 0, j = 0;
stack<int> nums;
stack<char> ops;
string result[n];
char ch;
while(j < n){
while(i++ < 7){
cin >> ch;
if(ch != '+' && ch != '-' && ch != 'x' && ch != '/'){
nums.push((int)(ch - '0'));
}else{
if(ch != '+' && ch != '-'){
// 数字栈中只有0个或1个数字,无法运算,等待下一次符号输入
if(nums.size() >= 2){
char op = ops.top();
// 如果此次运算符为 * 或者 /
// 查看上次运算符,如果是 * 或 / , 上次运算
// 并将运算结果压入数字栈中
// 如果是 + 或 - ,不执行上次运算,等待下次运算符时判断
if(op == 'x' || op == '/'){
int num2 = nums.top();
nums.pop();
int num1 = nums.top();
nums.pop();
nums.push(calculate(num1, num2, ops.top()));
ops.pop();
}
}
ops.push(ch);
}else{
// 数字栈中只有0个或1个数字,无法运算,等待下一次符号输入
if(nums.size() >= 2){
// 如果此次运算符为 + 或者 -, 则执行上次运算, 并将运算结果压入数字栈中
int num2 = nums.top();
nums.pop();
int num1 = nums.top();
nums.pop();
nums.push(calculate(num1, num2, ops.top()));
ops.pop();
}
ops.push(ch);
}
}
}
// 如果运算符栈内还有值,继续运算
while(!ops.empty()){
char op = ops.top();
int num2 = nums.top();
nums.pop();
int num1 = nums.top();
nums.pop();
nums.push(calculate(num1, num2, ops.top()));
ops.pop();
}
if(nums.top() == 24){
result[j++] = "Yes";
}else{
result[j++] = "No";
}
nums.pop();
i = 0;
}
j = 0;
while(j < n){
cout << result[j++] << endl;
}
return 0;
}
这道题有个坑,题目中描述乘号用字母 'x' 代替,刚开始没注意,直接用的字母 '*',总是不能满分,后来才发现,审题要仔细!