题目背景】
二十四点是一款著名的纸牌游戏,其游戏的目标是使用 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 + 4 × 3 = 24
5 + 4 × 5 × 5 = 105
7 - 9 - 9 + 8 = -3
5 × 6/5 × 4 = 24
3 + 5 + 7 + 9 = 24
1 × 1 + 9 - 9 = 1
1 × 9 - 5/9 = 9
8/5 + 6 × 9 = 55
6 × 7 - 3 × 6 = 24
6 × 4 + 4/5 = 24
import java.util.*;
public class Test201903_2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Stack<String> num=new Stack<String>();
Stack<String> symbol=new Stack<String>();
int n=sc.nextInt();
String YN="";
sc.nextLine();
for(int i=0;i<n;i++) {
String str=sc.nextLine();
int result=0;
num.push(str.charAt(0)+"");
for(int t=0;t<5;t+=2) {
if(str.charAt(t+1)=='x'||str.charAt(t+1)=='X') {
int b1=Integer.valueOf((String) num.pop());
int b2=str.charAt(t+2)-'0';
int a=b1*b2;
result=a;
num.push(""+a);
}else if (str.charAt(t+1)=='/') {
int b1=Integer.valueOf((String) num.pop());
int b2=str.charAt(t+2)-'0';
int a=b1/b2;
result=a;
num.push(""+a);
}else {
symbol.push(str.charAt(t+1)+"");
num.push(str.charAt(t+2)+"");
}
}
while(!symbol.isEmpty()) {
if(((String)symbol.pop()).equals("+")) {
result=Integer.valueOf((String)num.pop());
int b2=Integer.valueOf((String)num.pop());
result+=b2;
num.push(result+"");
}else {
result=Integer.valueOf((String)num.pop());
int b2=Integer.valueOf((String)num.pop());
result=-result+b2;
num.push(result+"");
}
}
num.clear();
symbol.clear();
if(result!=24) {
YN+="No\n";
}else {
YN+="Yes\n";
}
}
System.out.println(YN);
}
}