Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코딩응급실

프로그래머스: 콜라 문제 본문

Java

프로그래머스: 콜라 문제

Daeryuk Kim 2024. 1. 20. 13:38
class Solution {
    public int solution(int a, int b, int n) {
        int answer = 0;
        int leavings = 0; //나머지
        
        while(true){
            answer += b * ((n + leavings) / a); // 20 / 2 = 10
        
            leavings = n % a; // 20 % 2 = 0
        
            n /= a; // n = 10개 
            if (n < a) {
                answer++;
                break;
            }  
            
        }
        
        // 주인에게서 받은 콜라병의 개수
        return answer;
    }

    public static void main(String[] args) {

        int a=2, b=1, n=20;
        // 빈 병 2개를 주면 콜라 1병을 주신다. 빈 병이 지금 20개인 상태.
        Solution sol = new Solution();
        int result = sol.solution(a, b, n);
        System.out.println(result); 
    }
}

그냥 단순 수학 문제인줄 알았는데 제출하고 보니 올 킬 났다.

도대체 뭐가 문제인 것일까?

class Solution {
    public int solution(int a, int b, int n) {
        int answer = 0;
        int num = n;
        
        // 현재 병 개수가 교환가능기준인 a보다 작으면 끝이다.
        while(num >= a){ 
            
            answer += (num / a) * b; // 20 / 2 * 1 = 10
       
            num = (num / a) * b + num % a; // num = 10개 (몫   +  나머지)
        }
        
        // 주인에게서 받은 콜라병의 총 개수
        return answer;
    }

    public static void main(String[] args) {

        int a=2, b=1, n=20;
        // 빈 병 2개를 주면 콜라 1병을 주신다. 빈 병이 지금 20개인 상태.
        Solution sol = new Solution();
        int result = sol.solution(a, b, n);
        System.out.println(result); 
    }
}

answer에 넣어주는 식은 똑같은데, 현재 존재하는 병의 총개수 num을 계산하는 데에서 문제가 발생했던 것이다.

단순히 위와 같이 몫과 나머지를 더해서 구해주면 되는데 왜 이렇게 계속 복잡하게 생각하려고 하는 것인가 ㅠㅠ

쉽게 쉽게 생각하는 능력을 길러야겠다.