import java.util.Scanner;
public class dian24 {
public boolean isresult(String s) {
int tmp = 0;// 判断每位的值
int pre = 0;// 0+ 1- 2* 3/
int num = 0;// 存放计算结果
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1' && s.charAt(i + 1) == '0') {
tmp = 10;
i++;
} else if (s.charAt(i) >= '1' && s.charAt(i) <= '9') {
tmp = s.charAt(i) - '0';
} else {
if (pre == 0)
num = num + tmp;
else if (pre == 1)
num = num - tmp;
else if (pre == 2)
num = num * tmp;
else if (pre == 3)
num = num / tmp;
tmp = 0;
if (s.charAt(i) == '+')
pre = 0;
else if (s.charAt(i) == '-')
pre = 1;
else if (s.charAt(i) == '*')
pre = 2;
else if (s.charAt(i) == '/')
pre = 3;
}
}
if (pre == 0) {
num = num + tmp;
} else if (pre == 1) {
num = num - tmp;
} else if (pre == 2) {
num = num * tmp;
} else if (pre == 3) {
num = num / tmp;
}
if (num == 24) {
System.out.println(s);
return true;
} else
return false;
}
public static void main(String[] args) {
dian24 dian = new dian24();
Scanner s = new Scanner(System.in);
int count = 0;
int ans = 0;
int[] num = new int[4];
for (int i = 0; i < num.length; i++) {
num[count++] = s.nextInt();
}
String[] symbol = { "+", "-", "*", "/" };
for (int a = 0; a < 4; a++) {
for (int b = 0; b < 4; b++) {
for (int c = 0; c < 4; c++) {
StringBuilder sb = new StringBuilder();
sb.insert(0, num[0]);
sb.insert(sb.length(), symbol[a]);
sb.insert(sb.length(), num[1]);
sb.insert(sb.length(), symbol[b]);
sb.insert(sb.length(), num[2]);
sb.insert(sb.length(), symbol[c]);
sb.insert(sb.length(), num[3]);
if (dian.isresult(sb.toString())) {
ans++;
}
}
}
}
if (ans > 0) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
华为机试—24点游戏
最新推荐文章于 2023-03-21 10:05:01 发布