思路:先用getline()读取整个字符串。利用一个栈,对字符串中的运算数边运算边入栈:遇到乘除,取出栈顶元素和字符串中该乘除号的下一个字符(运算数)进行乘除运算,然后把结果压入栈中;如果遇到减号,则把下一个运算数取负号然后压入栈中。然后对栈中所有的运算数做加法,判断最后的结果是否为24即可。
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
int n;
string str;
cin >> n;
cin.get();
for(int i=0;i<n;i++)
{
int sum=0;
stack<int> s;
getline(cin,str);
for(int j=0;j<str.length();j++)
{
if(str[j]>='0'&&str[j]<='9')
{
s.push(str[j]-'0');
}
else if(str[j]=='x')
{
int temp=s.top()*(str[j+1]-'0');
s.pop();
s.push(temp);
j++;
}
else if(str[j]=='/')
{
int temp=s.top()/(str[j+1]-'0');
s.pop();
s.push(temp);
j++;
}
else if(str[j]=='-')
{
s.push(-(str[j+1]-'0'));
j++;
}
}
while(!s.empty())
{
sum+=s.top();
s.pop();
}
if(sum==24) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}
注意:栈的用法;
减法处的处理思想;
cin >> n后要处理空行;
str[i]-'0’换算成整数形式
只有当遇到运算符的时候才j++,跳过一下,遇到数字时直接存入,不跳过;
测试数据:
10
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
1x1+9-9
1x9-5/9
8/5+6x9
6x7-3x6
6x4+4/5