201903-2 二十四点
【题目背景】
二十四点是一款著名的纸牌游戏,其游戏的目标是使用3个加减乘除运算使得4张纸牌上数字的运算结果为24。
【题目描述】
定义每一个游戏由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。
【样例1输入】
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
【样例1输出】
yes
no
no
yes
yes
no
no
no
yes
yes
【样例1解释】
9+3+4x3=24
5+4x5x5=105
7-9-9+8=-3
5x6/5x4=24
3+5+7+9=24
1x1+9-9=1
1x9-5/9=9
8/5+6x9=55
6x7-3x6=24
6x4+4/5=24
import java.util.scanner;
import java.util.stack;
public class main {
public static void main(string[] args) {
scanner sc = new scanner(system.in);
int n = sc.nextint();
sc.nextline();
while (n > 0) {
string str = sc.nextline();
stack number = new stack<>();
char[] ch = str.tochararray();
int sum = 0;
int i = 0;
/*
* for (char c : ch) { system.out.println(c); }
*/
while (i < 7) {
if (i == 0) {
number.push(ch[i] - '0');
i++;
}else {
if (ch[i] == 'x') {
i++;
int left = number.pop();
number.push(left * (ch[i] - '0'));
i++;
//system.out.println("xxxxxxxx");
}else {
if (ch[i] == '/') {
i++;
int left = number.pop();
number.push(left / (ch[i] - '0'));
i++;
//system.out.println("///");
}else {
if (ch[i] == '-') {
i++;
number.push(-(ch[i] - '0'));
i++;
// system.out.println("--------------");
}else {
i++;
number.push(ch[i] - '0');
i++;
// system.out.println("+++++++++++");
}
}
}
}
}
sum = number.pop();
//system.out.println(sum);
while (!number.empty()) {
int right = number.pop();
sum += right;
// system.out.println(right);
// system.out.println(sum);
}
// system.out.println(sum);
if (sum == 24) {
system.out.println("yes");
} else {
system.out.println("no");
}
n--;
}
}
}