본문 바로가기
Baekjoon

[백준] 1431번 - 시리얼 번호 - Java

by jinjin98 2022. 12. 9.

 

Comparator 인터페이스를 이용해 문제에서 알려준 정렬 기준을 구현해서 풀었습니다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class p1431 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());
        String [] ar = new String[N];

        for(int i=0; i<N; i++) {

            ar[i] = br.readLine();
        }

        Arrays.sort(ar, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                //시리얼 번호 길이가 같으면
                if(o1.length() == o2.length()) {
                    int sumA = 0, sumB = 0;

                    for(int i=0; i<o1.length(); i++) {
                        if(o1.charAt(i) >= 48 && o1.charAt(i) <= 59)
                            sumA += Integer.parseInt(Character.toString(o1.charAt(i)));

                        if(o2.charAt(i) >= 48 && o2.charAt(i) <= 59)
                            sumB += Integer.parseInt(Character.toString(o2.charAt(i)));
                    }
                    //시리얼 번호에서 숫자합이 같으면 사전순으로
                    if(sumA == sumB)
                        return o1.compareTo(o2);

                    //시리얼 번호에서 숫자합이 다르면
                    //시리얼 번호에서 숫자합 오름차순
                    return sumA - sumB;
                }

                //시리얼 번호 길이 다르면 시리얼 번호 길이 오름차순
                return o1.length() - o2.length();
            }
        });

        for(int i=0; i<ar.length; i++) {
            System.out.println(ar[i]);
        }
    }
}

댓글