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]);
}
}
}
'Baekjoon' 카테고리의 다른 글
[백준] 1766번 - 문제집 - Java (0) | 2022.12.11 |
---|---|
[백준] 6996번 - 애너그램 - Java (0) | 2022.12.09 |
[백준] 5635번 - 생일 - Java (0) | 2022.12.04 |
[백준] 11557번 - Yangjojang of The Year - Java (0) | 2022.12.03 |
[백준] 2178번 - 미로 탐색 - Java (0) | 2022.11.29 |
댓글