각종 문제들

[프로그래머스] 코딩테스트 입문 - 옷가게 할인 받기

hunm719 2023. 4. 3. 19:40

문제 출처 : 프로그래머스

 

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
class Solution {
    public int solution(int price) {
        int answer = 0;
        
        if (price >= 500000) {
            answer = discount(price, 20);
        }
        
        else if (price >= 300000) {
            answer = discount(price, 10);
        }
        
        else if (price >= 100000) {
            answer = discount(price, 5);
        }
        else {
            answer = price;
        }
        
        return answer;
    }
    
    private int discount(int price, int percent) {
        return price - ((price * percent) / 100);
    }
}
cs

 

나름 잘 풀었다고 생각했지만... 20개의 테스트 케이스 중 2개에서 실패가 나왔다.

자세히 살펴보니 제한사항에서 소수점 이하를 버린 정수를 return하라는 부분을 놓쳤던 것이다.

 

예를 들어 price가 100,030 일 경우는 discount(100030, 5)가 호출되는데, return 값이 100030 - (500150 / 100)이 되고 (500150 / 100)은 5001.5지만 자동으로 내림되어 5001로 계산되어 최종 return 값이 100030 - 5001 = 95029 라는 잘못된 값이 나오게 된다.

 

 

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
class Solution {
    public int solution(int price) {
        int answer = 0;
        
        if (price >= 500000) {
            answer = discount(price, 0.2);
        }
        
        else if (price >= 300000) {
            answer = discount(price, 0.1);
        }
        
        else if (price >= 100000) {
            answer = discount(price, 0.05);
        }
        else {
            answer = price;
        }
        return answer;
    }
    
    private int discount(int price, double percent) {
        double discountedPrice = price - (price * percent);
        return (int) discountedPrice;
    }
}
cs

해당 문제는 입력값을 double percent로 변환하고 할인된 옷의 가격인 discountedPrice를 (int)로 형변환하는 것으로 해결할 수 있었다.