二十四点 (20 分)
定义每一个游戏由 4 个从 1-9 的数字和 3 个四则运算符组成,保证四则运算符将数字两两隔开,不存在括号和其他字符,运算顺序按照四则运算顺序进行。其中加法用符号 + 表示,减法用符号 - 表示,乘法用小写字母 x 表示,除法用符号 / 表示。在游戏里除法为整除,例如 2 / 3 = 0,3 / 2 = 1, 4 / 2 = 2。 老师给了你 n 个游戏的解,请你编写程序验证每个游戏的结果是否为 24 。
输入格式:
从标准输入读入数据。第一行输入一个整数 n,从第 2 行开始到第 n + 1 行中,每一行包含一个长度为 7的字符串,为上述的 24 点游戏,保证数据格式合法。
输出格式:
输出到标准输出。 包含 n 行,对于每一个游戏,如果其结果为 24 则输出字符串 Yes,否则输出字符串 No。
输入样例:
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
输出样例:
Yes
No
No
Yes
Yes
No
No
No
Yes
Yes
C++代码:
#include<bits/stdc++.h>
using namespace std;
int judge()
{
char code[10];
stack<int>s;
cin>>code;
for(int i=0;i<7;i++)
{
if(isdigit(code[i]))
{
s.push(code[i]-'0');
}
else if(code[i]=='x'||code[i]=='/')
{
int t=s.top();
s.pop();
if(code[i]=='x')
{
t*=(code[++i]-'0');
}
else
{
t/=(code[++i]-'0');
}
s.push(t);
}
if(code[i]=='+')
{
s.push(code[++i]-'0');
}
if(code[i]=='-')
{
s.push(-(code[++i]-'0'));
}
}
int all=0;
while(!s.empty())
{
int o=s.top();
s.pop();
all+=o;
}
if(all==24)return 1;
else return 0;
}
int main()
{
int n;
int xx[1005];
cin>>n;
for(int i=0;i<n;i++)
{
int j=judge();
xx[i]=j;
}
for(int i=0;i<n;i++)
{
if(xx[i])cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}