一、问题描述
给定四个整数,问:能不能算出数字24,若能则把所有结果显示出来。
二、解题思路及代码
将四个整数和三个符号随机打乱,并模拟计算,显示结果。
1 import java.util.*; 2 class Calcu24 3 { 4 public static void f(String[] ss) { 5 for(int k = 0; k <10000 * 10; k++) { //做10万次试验 6 String[] buf = new String[7] ;//四个整数、3个符号 7 for(int i = 0; i < 4; i++) buf[i] = ss[i];//输入的四个整数 8 for(int i = 4; i < 7; i++) buf[i] = random_op() ; //随机生成3个运算符 9 shuffle(buf) ;//洗牌 10 if(ji_suan(buf)) { //算牌,能算的出来就显示 11 show(buf) ;//显示结果 12 break; 13 } 14 } 15 } 16 17 public static String random_op() {//生成随机符号 18 int n = (int)(Math.random() * 4) ; 19 if(n==0) return "+" ; 20 if(n==1) return "-" ; 21 if(n==2) return "*" ; 22 return "/"; 23 } 24 25 public static void shuffle(String[] x) {//洗牌 26 for(int i = 0; i < x.length; i++) { 27 int j = (int)(Math.random() * x.length) ; 28 String t = x[i]; 29 x[i] = x[j]; 30 x[j] = t; 31 } 32 } 33 34 public static void show(String[] data) {//显示结果 35 Stack stk = new Stack() ; 36 for(int i =0; i <data.length; i++) { 37 if(data[i].equals("+") || data[i].equals("-") || data[i].equals("*") ||data[i].equals("/")) { 38 stk.push("("+stk.pop()+data[i] + stk.pop()+")") ; 39 } else { 40 stk.push(data[i]) ; 41 } 42 } 43 System.out.println(stk.pop()) ; 44 } 45 46 public static boolean ji_suan(String[] data) { 47 Stack stk = new Stack() ; 48 try{ 49 for(int i =0; i <data.length; i++) { 50 if(data[i].equals("+") || data[i].equals("-") || data[i].equals("*") ||data[i].equals("/")) { 51 int a = Integer.parseInt((String)stk.pop()) ; 52 int b = Integer.parseInt((String)stk.pop()) ; 53 stk.push(op(a,b,data[i]) + "");//计算的结果压栈 54 } else { 55 stk.push(data[i]) ; 56 } 57 } 58 }catch(Exception e) { 59 return false; 60 } 61 if(stk.size()==1 && stk.pop().equals("24")) return true ; 62 return false ; 63 } 64 65 public static int op(int a, int b, String oper) throws Exception { //计算 66 if(oper.equals("+")) return a + b ; 67 if(oper.equals("-")) return a - b ; 68 if(oper.equals("*")) return a * b ; 69 if(a%b!=0) throw new Exception("not /") ; 70 return a/b ; 71 } 72 73 public static void main(String[] args) 74 { 75 Scanner scan = new Scanner(System.in) ; 76 while(true) { 77 System.out.print("请输入四个整数:") ; 78 String[] ss = scan.nextLine().split(" ") ; 79 System.out.println(Arrays.toString(ss)) ; 80 f(ss); 81 } 82 } 83 }