第一题(格式化输出)
package ccf201903; import java.util.Arrays; import java.util.Scanner; public class p1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double[] a = new double[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } Arrays.sort(a); double max = a[n - 1]; double min = a[0]; double mid; if (n % 2 == 0) { mid = (a[n / 2 - 1] + a[n / 2]) / 2; } else { mid = a[n / 2]; } String res; if (mid - (int) mid == 0) { res = "%.0f %.0f %.0f"; } else { res = "%.0f %.1f %.0f"; } System.out.printf(res, max, mid, min); } }
第二题(经典24点问题,使用栈解决;ccf不支持switch)
package ccf201903; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class p2 { public static void main(String[] args) throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bf.readLine()); String[][] line = new String[n][]; for (int i = 0; i < n; i++) { line[i] = bf.readLine().split(""); } for (int i = 0; i < n; i++) { if (getFin(line[i]) == 24) { System.out.println("Yes"); } else { System.out.println("No"); } } } public static int getFin(String[] line) { int[] num = new int[4]; int index = 1; num[0] = Integer.parseInt(line[0]); int fin = 0; for (int i = 1; i < line.length; i += 2) { if (line[i].equals("+")) { num[index] = Integer.parseInt(line[i + 1]); index++; } else if (line[i].equals("-")) { num[index] = Integer.parseInt(line[i + 1]) * (-1); index++; } else if ((line[i].equals("x"))) { num[index] = Integer.parseInt(line[i + 1]); int a = num[index - 1]; int b = num[index]; int res = a * b; num[index - 1] = res; num[index] = 0; } else if ((line[i].equals("/"))) { num[index] = Integer.parseInt(line[i + 1]); int a = num[index - 1]; int b = num[index]; int res = a / b; num[index - 1] = res; num[index] = 0; } } for (int i = 0; i < num.length; i++) { fin += num[i]; } return fin; } }