思路:鸡头从0到n遍历,找到符合条件的一组解就可,然后可以break,实质上是解一元一次方程组(或者说是二元一次方程组)
实现:
import java.util.Scanner;
public class ChickenAndRabbitCage {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int flag=0;
for(int i=0;i<n;i++){
int heads=scan.nextInt();
int lags=scan.nextInt();
for(int chichenheads=0;chichenheads<=heads;chichenheads++){
int rabbitheads=heads-chichenheads;
if(chichenheads*2+rabbitheads*4==lags){
flag=1;
System.out.println("number of chichen is "+chichenheads);
System.out.println("number of rabbit is "+ rabbitheads);
break;
}
}
if(flag!=1){
System.out.println("No answer");
}
}
scan.close();
}
}