题解 | #24点运算# 多层for循环解决
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); scanner.close(); String[] strs = input.split(" "); int[] nums = new int[4]; HashMap<Integer, Character> map = new HashMap<>(); map.put(11, 'J'); map.put(12, 'Q'); map.put(13, 'K'); map.put(1, 'A'); for (int i = 0; i < 4; i++) { if (strs[i].equals("joker") || strs[i].equals("JOKER")) { System.out.println("ERROR"); return; } if (strs[i].equals("A")) { nums[i] = 1; } else if (strs[i].equals("J")) { nums[i] = 11; } else if (strs[i].equals("Q")) { nums[i] = 12; } else if (strs[i].equals("K")) { nums[i] = 13; } else { nums[i] = Integer.valueOf(strs[i]); } } boolean flag = false; char[] ops = {'+', '-', '*', '/'}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == j) { continue; } for (int k = 0; k < 4; k++) { if (k == i || k == j) { continue; } for (int l = 0; l < 4; l++) { if (l == i || l == j || l == k) { continue; } for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) { for (int z = 0; z < 4; z++) { int num1 = nums[i]; int num2 = nums[j]; int num3 = nums[k]; int num4 = nums[l]; char op1 = ops[x]; char op2 = ops[y]; char op3 = ops[z]; if (op1 == '/' && num1 % num2 != 0) { continue; } int res1 = calculate(num1, num2, op1); int res2 = calculate(res1, num3, op2); int res3 = calculate(res2, num4, op3); if (res3 == 24) { System.out.println(getString(num1, map) + op1 + getString(num2, map) + op2 + getString(num3, map) + op3 + getString(num4, map)); flag = true; break; } } if (flag) { break; } } if (flag) { break; } } if (flag) { break; } } if (flag) { break; } } if (flag) { break; } } if (flag) { break; } } if (!flag) { System.out.println("NONE"); } } private static int calculate(int num1, int num2, char op) { if (op == '+') { return num1 + num2; } else if (op == '-') { return num1 - num2; } else if (op == '*') { return num1 * num2; } else { return num1 / num2; } } private static String getString(int num, HashMap<Integer, Character> map) { if (num == 1) { return "A"; } else if (num <= 10) { return String.valueOf(num); } else { return String.valueOf(map.get(num)); } } }