CCF2019-03-2 二十四点 Java实现
思路:只计算乘除法,遇到减号就把符号赋给下一个数字,最后再将栈中所有剩余的数字累加并进行判断即可。
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int res;
for (int i = 0; i < n; i++) {
String s = scan.next();
Stack<Integer> k1 = new Stack<>();
int j = 0;
res = 0;
while (j < s.length()) {
if (s.charAt(j) > '0' && s.charAt(j) <= '9') {
k1.push(s.charAt(j) - '0');
} else if (s.substring(j, j + 1).equals("x")) {
int a = k1.peek();
k1.pop();
k1.push(a * (s.charAt(j + 1) - '0'));
j++;
} else if (s.substring(j, j + 1).equals("/")) {
int a = k1.peek();
k1.pop();
k1.push(a / (s.charAt(j + 1) - '0'));
j++;
} else if (s.substring(j, j + 1).equals("-")) {
k1.push((s.charAt(j + 1) - '0') * -1);
j++;
}
j++;
}
while (!k1.isEmpty()) {
res += k1.pop();
}
if (res == 24) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}