Java递归实现算24

 

题目就是我们平时玩过的算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");
}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值