java兔子_JAVA经典兔子问题

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....

package org.llh.demo01;

import java.util.ArrayList;

public class DemoTest002 {

static ArrayList list = new ArrayList();

int number ;//计算后一个月的兔子数量

public static void main(String[] args){

DemoTest002 st = new DemoTest002();

st.fun();

st.out();

}

private void fun(){ //将12个月的兔子数量保存进list链表集合内

list.add(1);

list.add(1); //前两个月的兔子数量

for(int i = 3;i<=12;i++){

number = list.get(i-2)+list.get(i-3);

list.add(number);

}

}

private void out(){//输出12个月的兔子数量

int i =1;

for(int j:list){

System.out.println("第"+(i++)+"个月的兔子数量是"+j);

}

}

}

eb97944bfc3367be6b71ebd9e4b26fcb.png

12个月总数

package org.llh.demo01;

public class DemoTest001 {

static int MONTH[] = {1,2,3,4,5,6,7,8,9,10,11,12}; //第几个月

static int TYPE = 1; //一对生几对

private int getCount(int month, int type){

int sum = 0;

if(month == 1 || month ==2){

sum = 1;

}else{

sum = getCount(month - 1,1) + getCount(month - 2,1)*type;

}

return sum;

}

public static void main(String[] args) {

int count=0;

for(int a:MONTH){

int sum = (new DemoTest001()).getCount(a, TYPE);

count = sum+count;

}

System.out.println(count);

}

}

9d5a15a6ea42b5c4c1510f36225392d8.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值