经典面试题------农夫养牛

来源:互联网 发布:阿里云香港主机连不上 编辑:程序博客网 时间:2024/04/30 09:18

一个农夫养了一头牛,三年后,这头牛每年会生出1头牛,生出来的牛三年后,又可以每年生出一头牛……问农夫10年后有多少头牛?n年呢?(用JAVA实现)

思路一:

public class Cow {
   
private int age;
   
public Cow(){
        age
= 0;
    }
   
public Cow play(){
        age
++;
       
return age > 3 ? new Cow():null;
    }
   
   
public static void main(String[] args) {
        List
<Cow> list = new ArrayList<Cow>();
        list.add(
new Cow());
       
for(int i = 0; i <= 10;i++){
           
for(int j =0;j<list.size();j++){
                Cow cow
= list.get(j).play();
               
if(cow != null)
                    list.add(cow);这里集合跟对象的运用很是不错!
            }
        }
        System.out.println(
"10年后,共有:" + list.size());
    }
}

 

思路二:

public class Cow {
   
public static int count = 0;
   
public Cow(int year){
        count
++;
       
for(int i=3+year;i<=10;i++){
           
new Cow(i); 这种面向对象的思路很是不错
        }
    }

   
public static void main(String[] args) {
       
new Cow(0);
        System.out.println(count);
    }
}

 

思路三:递归思想

public class Cow {
   
static int count = 1;
   
private static void feedCow(int year,int age){
        year
++;
        age
++;
       
if(year<=30){
           
if(age>=3){只有当牛的年龄达到三岁的话,才会每年产一头
                count
++;
                feedCow(year,
0);
            }
            feedCow(year,age);
        }
    }

   
public static void main(String[] args) {
       
new Cow().feedCow(0, 0);
        System.out.println(count);
    }
}

 

思路四:

public class CowBreed
{
   
public static void main(String args[])
    {
       
final int size = 100;               //可以根据需要,设置为所需要计算的最大年限
        long[] num = new long[size + 1];
        num[
0] = num[1] = num[2] = 0;
       
for(int i = 3; i <= size; ++ i)
        {
            num[i]
= num[i - 1] + 1 + num[i - 3];
            System.out.println(
"" ++ "年,牛的数量为:" + (num[i] + 1));
        }
    }
}

原创粉丝点击