递归:兑换问题

/**
 * 28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,够28人喝?假如是50人,又需要买
多少瓶可乐?(需写出分析思路)
 * 分析:解决问题需要进行分步进行。
 * 1. 首先写出n瓶可以兑换出多少瓶
 * 2. 再用循环求出1...n瓶中,刚好满足条件的个数。
 *
 * @author Barudisshu
 */
public class TestDrink {

    public static void main(String[] args) {

        int people = 28;
        int change = 3;
        int buys = count(people, change, 0);
        int got = exchange(buys,change,0);
        System.out.println(people + "人需要买" + buys+"瓶,并且可以兑换"+got+"瓶");
    }

    /**
     * 可以兑换的个数
     */
    public static int exchange(int bots, int con, int count) {
        if (bots < con) {           // 如果小于置换条件
            count = 0;
        } else if (bots == con) {   // 刚好等于置换条件
            count = 1;
        } else {                    // 大于置换条件
            if ((bots / con + bots % con) >= con) {     // 可以再次置换
                count = bots / con + exchange(bots / con + bots % con, con, count);
            } else  // 不可以再次置换
                count = bots / con;
        }
        return count;
    }

    /**
     * 获得实际个数
     */
    public static int count(int people, int con, int count) {
        int i = 0;
        while (true) {
            int total = i + exchange(i, con, count);
            if (total >= people)
                break;
            i++;
        }
        return i;
    }

}



转载于:https://my.oschina.net/Barudisshu/blog/420114

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值