TIL

[코테연습] 1518. Water Bottles

크라00 2024. 7. 7. 18:55

- 반복문 문제

 

https://leetcode.com/problems/water-bottles/description/?envType=daily-question&envId=2024-07-07

 

- 문제해석

1. 초기에 주어지는 bottle 값이 있다.

2. 교환할 수 있는 exchange 값이있다.

3. bottle 을 계속해서 교환하여 더이상 교환 할수 없을 때까지  반복했을 때, 마신 bottle 의 값을 리턴해라.

 

- 문제풀이

1. while 문으로 반복문을 선언한다.

 1-1. bottle 이 exchnage 값보다 클때까지만 반복한다.

2. 교환한 값 change 를 bottle / exchange 로 초기화한다.

3. 교환할 수 없는 값 remainBottle 을 bottle % exchange 로 초기화한다.

4. change 의 값을 더하여 리턴한다.

 

class Solution {
    public int numWaterBottles(int numBottles, int numExchange) {
        
        //drink
        int bottle = numBottles;
        int count = numBottles;
        while(bottle >= numExchange) {
            //not drink
            int changed = bottle/numExchange;
            int remainBottle = bottle%numExchange;

            //after
            bottle = changed+remainBottle;
            count+=changed;
        }
        return count;
    }
}