반응형

문제

준원이는 저번 주에 살면서 처음으로 코스트코를 가 봤다. 정말 멋졌다. 그런데, 몇 개 담지도 않았는데 수상하게 높은 금액이 나오는 것이다! 준원이는 영수증을 보면서 정확하게 계산된 것이 맞는지 확인해보려 한다.

영수증에 적힌,

  • 구매한 각 물건의 가격과 개수
  • 구매한 물건들의 총 금액

을 보고, 구매한 물건의 가격과 개수로 계산한 총 금액이 영수증에 적힌 총 금액과 일치하는지 검사해보자.


입력

첫째 줄에는 영수증에 적힌 총 금액 X가 주어진다.

둘째 줄에는 영수증에 적힌 구매한 물건의 종류의 수 N이 주어진다.

이후 N개의 줄에는 각 물건의 가격 a와 개수 b가 공백을 사이에 두고 주어진다.


출력

구매한 물건의 가격과 개수로 계산한 총 금액이 영수증에 적힌 총 금액과 일치하면 Yes를 출력한다. 일치하지 않는다면 No를 출력한다.


제한

  •  1≤X≤1000000000
  •  1≤N≤100
  •  1≤a≤1000000
  •  1≤b≤10

예제 입력

예제입력 예제출력
260000
4
20000 5
30000 2
10000 6
5000 8
Yes
250000
4
20000 5
30000 2
10000 6
5000 8
No

풀이 및 코드

-> 간단한 문제라고 생각했는데도 틀렸다고 나와서 당황했다. 알고보니 Yes, No로 출력하지않고 yes, no라고 출력해서 틀린 것이었다. 주어진 조건을 놓치지 않는 연습이 더 필요해 보인다.

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int totalPrice = Integer.parseInt(sc.nextLine()); // 총 금액
        int totalCount = Integer.parseInt(sc.nextLine()); // 총 구매종류 갯수
        
        int[] price = new int[totalCount]; // 가격 담을 변수
        int[] count = new int[totalCount]; // 갯수 담을 변수
        String judge = "No"; // 금액이 맞는지 아닌지 판단
        int sumPrice = 0;
        
        // 물건 가격과 갯수 담기
        for(int i=0;i<totalCount;i++){
            String totalTemp = sc.nextLine();
            String[] temp = totalTemp.split(" ");
            price[i] = Integer.parseInt(temp[0]);
            count[i] = Integer.parseInt(temp[1]);
            sumPrice += price[i]*count[i];
        }
        
        if(sumPrice==totalPrice){
            judge = "Yes";
        }
        
        System.out.println(judge);
        
    }
}

 

변수를 줄이고, 간결하게 리팩토링한 코드는 아래와 같다.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int totalPrice = sc.nextInt(); // 총 금액
        int totalCount = sc.nextInt(); // 총 구매종류 갯수
        sc.nextLine(); // 개행문자 처리
        
        int sumPrice = 0;
        
        // 물건 가격과 갯수 계산
        for (int i = 0; i < totalCount; i++) {
            int itemPrice = sc.nextInt();
            int itemCount = sc.nextInt();
            sumPrice += itemPrice * itemCount;
        }
        
        System.out.println(sumPrice == totalPrice ? "Yes" : "No");
    }
}
반응형

+ Recent posts