解题思路:
1.使用栈来分别存储数字和操作符
2.如果是数字,直接放入数字栈
3.如果是操作符:如果是乘法或者除法操作符,可以直接弹出数字栈的顶部两个数用来计算,计算 结果放入数字栈
如果是加法,优先级低于乘除,不能直接计算,放入操作符栈
如果是减法,优先级低于乘除,不能直接计算,当成加法入栈,此外数字栈顶部 数字要改变符号
4.第一轮遍历后计算完所有乘除,开始计算加法,每次从数字栈弹出两个数,操作符栈弹出一个操作符,数字相加后放入数字栈,直到操作符栈为空为止
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
while(n--)
{
string str;
cin>>str; //输入字符串
stack<int> num; //存储数的栈
stack<char> op; //存储操作符的栈
for(int i=0;i<str.length();i++)
{
if(i%2==0) //这些位置是数字
{
int t=str[i]-'0'; //字符转数字
num.push(t);
}
//如果前一个字符是操作符
if(i!=0&&str[i-1]=='x') //乘除直接计算
{
int a=num.top();
num.pop();
int b=num.top();
num.pop();
int t=a*b;
num.push(t);
}
else if(i!=0&&str[i-1]=='/')
{
int a=num.top();
num.pop();
int b=num.top();
num.pop();
int t=b/a;
num.push(t);
}
else if(i!=0&&str[i-1]=='+') //加法入栈
{
op.push(str[i-1]);
}
else if(i!=0&&str[i-1]=='-') //减法改变符号后入栈
{
op.push('+');
int t=num.top();
num.pop();
t=t*(-1);
num.push(t);
}
}
while(!op.empty()) //处理加法和剩余数字
{
char t=op.top();
op.pop();
int a=num.top();
num.pop();
int b=num.top();
num.pop();
int tt=a+b;
num.push(tt);
}
int s=num.top();
if(s==24) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}