题目来源
碎碎念
加号、减号是同一层
乘法、除法是同一层
优先执行乘除
代码
#include <iostream>
#include <fstream>
using namespace std;
#define STRLENGTH 7
int main() {
ifstream cin("in.txt");
// 数字(4个): 1- 9
// 运算符(3个): 加减乘除, !!!除为整除!!!
int N;
cin>>N;
while (N-- > 0) { // 判断 N 次,是否为四则运算
string str;
cin>>str;
int num[4]; // 存放数字
char op[3]; // 存放运算符
int indexNum = 0, indexOp = 0;
int index = 0;
while (index < STRLENGTH) { // 遍历每一个字符
if (index % 2 == 1) { // 运算符的位置
//cout<<"op"<<endl;
char c = str[index];
if (c == '+' || c == '-') { // 是加号/ 减号, 存储到op
op[indexOp++] = c;
//cout<<" +/-"<<endl;
}
else { // 是 乘号或者除号, 当即执行
int first = num[--indexNum];
int second = str[++index] - '0';
//cout<<index<<" * "<<str[index]<<endl;
if (c == 'x') {
num[indexNum++] = first * second;
}
else {
num[indexNum++] = first / second;
}
//cout<<first<<" "<<second<<endl;
//cout<<" "<<c<<" "<<num[indexNum - 1]<<endl;;
}
}
else { // 存储数字
//cout<<"num"<<endl;
num[indexNum++] = str[index] - '0';
}
++index;
}
int j = 0;
for (int i = 0; i < indexOp; ++i) { // 剩下加减号, 按顺序执行
int first = num[j++];
int second = num[j++];
char c = op[i];
if (c == '+') {
num[--j] = first + second;
}
else {
num[--j] = first - second;
}
}
if (num[j] == 24) {
cout<<"Yes"<<endl;
}
else {
cout<<"No"<<endl;
}
}
return 0;
}