Skip to main content

[Java] 132267 콜라 문제


1. 문제

콜라 문제


2. 오답코드

  1. 현재 빈병 개수를 담을 변수 n을 선언
  2. 현재 빈병의 개수가 a보다 크거나 같은 동안만 아래의 로직을 실행한다.
    1. int newCola = 새로 받는 콜라 = ( bottles / a ) * b;
    2. answer += newCola
    3. 현재 빈병의 개수 = bottles를 a로 나눈 나머지 + newCola
class Solution {
    public int solution(int a, int b, int n) {
        int answer = 0; // 받을 수 있는 콜라 개수
        int bottles = n; // 현재 빈병 개수
        
        while(bottles < a) { // 병이 a 이상이면 바꿀 수 있음
            int newCola = (bottles / a) * b; // 새로 받는 콜라
            answer += newCola;
            bottles = (bottles % a) + newCola; // 남은 병 + 새 콜라 마신 후 나온 빈 병
        }
        
        return answer;
    }
}

image.png


틀린 이유

  • while문에서 조건문 부호를 잘못 씀
    • 보유한 빈 병의 개수가 a 이상일 때만 콜라를 교환할 수 있다고 했으니까
    • bottles >= a 로 수정함

3. 정답코드

class Solution {
    public int solution(int a, int b, int n) {
        int answer = 0; // 받을 수 있는 콜라 개수
        int bottles = n; // 현재 빈병 개수
        
        while(bottles >= a) { // 병이 a 이상이면 바꿀 수 있음
            int newCola = (bottles / a) * b; // 새로 받는 콜라
            answer += newCola;
            bottles = (bottles % a) + newCola; // 남은 병 + 새 콜라 마신 후 나온 빈 병
        }
        
        return answer;
    }
}