CCF:201903-2二十四点(JAVA版)
2020-03-06 本文已影响0人
巨鹿lx
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
while(n-->0) {
char[] a = scanner.nextLine().toCharArray();
if(value(a)==24) {
System.out.println("Yes");
}else {
System.out.println("No");
}
}
}
private static int value(char[] a) {
LinkedList<String> que = new LinkedList<>();
int l = 0,r = 6;
while(l<=r) {
if(a[l]<='9'&&a[l]>='0') {//数字
if(que.size()>0) {
String op = que.pollLast();
if(op.equals("x")||op.equals("/")) {
int num = Integer.parseInt(que.pollLast());
que.add(""+compute(num,op,a[l]-'0'));
}else {
que.add(op);
que.add(""+a[l]);
}
}else {
que.add(""+a[l]);
}
l++;
}else {//符号
que.add(""+a[l++]);
}
}
while(que.size()>1) {
int na = Integer.parseInt(que.pollFirst());
String op = que.pollFirst();
int nb = Integer.parseInt(que.pollFirst());
que.addFirst(""+compute(na, op, nb));
}
return Integer.parseInt(que.getFirst());
}
private static int compute(int num, String op, int i) {
switch(op) {
case "+": return num+i;
case "-": return num-i;
case "x": return num*i;
case "/": return num/i;
}
return 0;
}
}
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