JAVA 常用算法学习记录(穷举算法)

时间:2021-01-31 11:13:22

问题:今有鸡兔同笼,上有三十五头,下有九十四足,问鸡兔各多少


java 实现代码:

public static Map<String,Object> qiongju(int head,int foot){
int result,i , j,chicken = 0,rabit = 0;
result = 0;
for(i = 0 ; i<= head;i++){
j = head - i;
if((i*2 + j*4 )== foot){
result = 1;
chicken = i;//鸡
rabit = j;//兔
}
  }
Map<String,Object> hashMap = new HashMap<>();
hashMap.put("result",result);
hashMap.put("chicken",chicken);
hashMap.put("rabit",rabit);
  return  hashMap;
}


public static void main(String[] args){
Map<String,Object> hashMao = qiongju(35, 94);
if(hashMao.get("result").equals((int)1)){
System.out.println("求解成功!!");
System.out.println("鸡有:"+hashMao.get("chicken"));
System.out.println("兔有:"+hashMao.get("rabit"));

} else{
System.out.println("无法求解");
}

}


图:

JAVA 常用算法学习记录(穷举算法)