递归问题

2021-05-13  本文已影响0人  康大侠
  1. 买汽水

转载地址

题目:1块钱1瓶汽水,2个空瓶可以换一瓶汽水,3个瓶盖可以换一瓶汽水,问: 20块钱可以喝多少瓶汽水?

初始化
有20元钱,money = 20;
瓶盖和空瓶为0,bottle = 0; cap = 0;
定义一个方法,返回值为总的瓶数。
int buyWater(int money,int bottle,int cap)

public class BuyWaterDemo {
    public static void main(String[] args) {
        int money = 20;
        int bottle = 0;
        int cap = 0;
        int sum = buyWater(money, bottle, cap);
        System.out.println(sum+"瓶汽水。");
    }
    public static int buyWater(int money,int bottle,int cap) {
        int num = 0;
        if(money>=1) {
            num++;
            bottle++;
            cap++;
            num += buyWater(money-1,bottle,cap);
        }else if(bottle>=2) {
            num++;
            bottle++;
            cap++;
            num += buyWater(money,bottle-2,cap);
        }else if(cap>=3) {
            num++;
            bottle++;
            cap++;
            num += buyWater(money,bottle,cap-3);
        }
            return num; 
    }
}
上一篇下一篇

猜你喜欢

热点阅读