题目就是我们平时玩过的算24小游戏,输入四个数,判断是否能算出24;
若可以输出yes,若不行输出no
如:输入: 5 5 5 1
输出:Yes
import java.util.Scanner; public class 算24 { public static boolean getResult(String line){ String[] str = line.split(" ");//把字符串利用空格分开成数组 if(str.length == 1){//递归出口,只剩下一个数的时候就判断时候为24 if(isZero(Math.abs(Double.parseDouble(str[0])-24))){ return true; } return false; } String s = ""; String a = ""; String b = ""; String c = ""; String d = ""; String e = ""; for(int i=0; i<str.length-1; i++){ for(int j=i+1; j<str.length; j++){ for(int ij=0; ij<str.length; ij++){//讲当前没有计算的数先存起来 if(ij!=i && ij!=j){ s += str[ij]+" ";//+ a += str[ij]+" ";//- b += str[ij]+" ";//- c += str[ij]+" ";//* d += str[ij]+" ";// / e += str[ij]+" ";// / } } double n = Double.parseDouble(str[i]);//讲得到的字符串转换为浮点型 double m = Double.parseDouble(str[j]); double num; num = n+m;//相加时 s += Double.toString(num); if(getResult(s)) return true; num = n-m;//相减时,因为两个不同的书互减答案不一样 a += Double.toString(num); if(getResult(a)) return true; num = m-n;//相减时 b += Double.toString(num); if(getResult(b)) return true; num = n*m;//相乘时 c += Double.toString(num); if(getResult(c)) return true; if(!isZero(m)){//两个不相同的书互除答案不一样,还要判断分母不能0 num = n/m; d += Double.toString(num); if(getResult(d)) return true; } if(!isZero(n)){//相除 num = m/n; e += Double.toString(num); if(getResult(e)) return true; } s = a = b = c = d = e = "";//将字符串重置,接着枚举 } } return false; } private static boolean isZero(double num){//因为是浮点数,所以不能用==判断是否等于0,只能判断在哪个范围 if(num < Math.pow(10, -6)) return true; return false; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String line = sc.nextLine(); getResult(line); if(getResult(line)){ System.out.println("Yes"); }else{ System.out.println("No"); } } }