换酒问题

换酒问题

一、题目描述

由numBottles瓶酒,可以用numExchange个空酒瓶换一个新酒。问最多可以喝多少瓶酒?

二、题目分析

这里空酒瓶包括新换的酒喝完的酒瓶。就是原来总酒瓶numbootles需要加上新换的酒喝完的酒瓶。

三、解题思路

方法1
一次性喝完一次性兑换。创建一个变量num来记录喝过酒的瓶数,初始化为numbootles;然后算出新换的酒newbootles。用numbootles/numexchange,即可。给num加上newbootles。再计算当前的空瓶子数。numbootles = newbootles + numbootles%numexchange,就是新换的酒瓶,再加上上次剩的酒瓶。
代码实现

public int numWaterBottles(int numBottles, int numExchange) {
    
    int num = numBoottles;
    while(numBoottles >= numExchange){
      
        int newBoottle = numBoottles/numExchange;
        numBootles = newBottles+(numBottles%numExchange);
        num = num + newBottles;
    }
    return num;

}

方法2
第一次喝完后,每换一瓶喝一瓶,再换新的一瓶。每次从第一个瓶子里减去交换的瓶子,再加上新喝完的瓶子。实际就是只用3个瓶子换一瓶酒。但是需要换一瓶喝一瓶。
代码实现

int bottle = numBottles;
        int ans = numBottles;

        while(bottle >= numExchange){
            bottle -= numExchange;
            ans++;
            bottle++;
        }

        return ans;
posted @ 2022-09-03 00:01  z_coding  阅读(65)  评论(0)    收藏  举报