本次针对上次递归遗留问题编写出对于代码.当然,解决方案很多,只供参考.
有一对兔子,从出生后第三个月起每月都生一对兔子,小兔子3个月后又生一对兔子,加入兔子都不死,问第20个月后兔子对数是多少??
这道题依然用递归的方法解决
```
public static int arithmetic(int number){
if(number == 1|| number == 2){
return 1;
}else{
return arithmetic(number - 1) + arithmetic(number - 2);
}
}
啤酒问题:
啤酒2元一瓶,4个盖子可以换一瓶,两个空瓶可以换一瓶
问10元可以喝多少瓶?
剩余多少空瓶和盖子。
方法一
//递归
/*
* 啤酒2元一瓶,4个盖子可以换一瓶,两个空瓶可以换一瓶,问10元可以喝多少瓶?
* 买酒->喝酒->兑换->喝酒->兑换-喝酒->兑换......
* 啤酒 空瓶 盖子
* 5 0 0
* 0 5 5
* 2+1 1 1
* 0 4 4
* 2+1 0 0
* 0 3 3
* 1 1 3
* 0 2 4
* 1+1 0 0
* 0 2 2
* 1 0 2
* 0 1 3
* 结果: 15啤酒1空瓶3瓶盖
*/
public class FileDemo04 {
public static void main(String[] args) {
int beers = getBeer(buyBeer(20), 0, 0);
System.out.println("最多可以喝" + beers + "瓶啤酒");
}
public static int getBeer(int beer, int bottle, int cap) {
//递归终止条件:空瓶=1 瓶盖<4 未喝的啤酒为0
if (bottle == 1 && cap < 4 && beer == 0) {
System.out.println("剩余空瓶个数 = " + bottle);
System.out.println("剩余瓶盖个数 = " + cap);
return 0;
}
//否则进行递归
else {
//喝掉未喝的啤酒,累加剩余空瓶
bottle += beer;
//喝掉未喝的啤酒,累加剩余瓶盖
cap += beer;
//本次兑换啤酒总数
int extraBeer = bottle / 2 + cap / 4;
//兑换后的空瓶数
bottle %= 2;
//兑换后的瓶盖数
cap %= 4;
//返回本次喝掉的啤酒数
return beer + getBeer(extraBeer, bottle, cap);
}
}
public static int buyBeer(int money) {
return money / 2;
}
}
方法二
//啤酒问题两种解法-->静态变量的使用
/*
* 啤酒:
* 2元可以买一瓶啤酒,2个空瓶可以换一瓶
* 4个盖子可以换一瓶。
*
* 问:10元可以喝多少瓶?剩余多少空瓶和多少盖子。
*
* */
public class Pijiu_01 {
// 定义一个静态变量存储可以喝的酒的数量
private static int totalCount ;
// 定义两个变量存储上一轮多出来的瓶子数量和盖子数量
private static int preGaiziNum , prePingziNum;
public static void main(String[] args){
calc(10);
System.out.println(totalCount);
System.out.println(preGaiziNum);
System.out.println(prePingziNum);
}
// 定义一个方法去计算可以喝多少瓶酒
public static void calc(int money){
// 10 -> 5瓶 -> 多出了5个盖子5个瓶子 -> 6元
// 计算当前钱可以买多少瓶酒
int jiuNums = money / 2;
totalCount+=jiuNums;
// 多出一些盖子和瓶子数,换算成钱,继续去购买!
// 必须加上上一轮多出来的盖子数和瓶子数
int gaiziNums = preGaiziNum + jiuNums;
int pingZiNums = prePingziNum + jiuNums;
// 换算成钱
int totalMoney = 0 ;
if(gaiziNums>=4){
// 可以换算成钱的
totalMoney+=((gaiziNums / 4)*2);
// 多出来的盖子存起来作为下一轮使用
preGaiziNum = gaiziNums % 4;
}else{
preGaiziNum = gaiziNums;
}
if(pingZiNums>=2){
// 可以换算成钱的
totalMoney+=((pingZiNums / 2)*2);
// 多出来的瓶子存起来作为下一轮使用
prePingziNum = pingZiNums % 2;
}else{
prePingziNum = pingZiNums;
}
if(totalMoney >=2){
calc(totalMoney);
}
}
}