[ 백준 ] 1427 소트인사이드

codesver·2022년 11월 29일
0

Baekjoon

목록 보기
6/72
post-thumbnail

Solution

주어진 숫자들의 digit을 정렬하면되는 간단한 문제이다.

Counter를 이용하여 해결하는 것이 가장 정석적인 풀이법이다.

private static void solution() throws IOException {
    int[] counter = new int[10];
    int num = Integer.parseInt(reader.readLine());

    while (num != 0) {
        counter[num % 10]++;
        num = num / 10;
    }

    for (int i = 9; i >= 0; i--)
        result.append(String.valueOf(i).repeat(counter[i]));
}

-> 주어진 숫자들의 digit을 count하여 counter에 저장한다.

-> 이후 counter를 반복하며 정렬된 숫자를 출력한다.

위와 같은 방법은 정석적이지만 사실 stream을 통해 더 간단하게 해결할 수 있다.

다만, 성능이 소폭 감소한다는 단점이 있기 때문에 고려해서 사용해야 한다.

(문제에서는 12ms의 성능만이 감소하였기 때문에 큰 문제는 없다.)

private static void solution() throws IOException {
    result.append(Arrays.stream(reader.readLine().split(""))
            .sorted((o1, o2) -> Integer.parseInt(o2) - Integer.parseInt(o1))
            .collect(Collectors.joining()));
}

-> String.split() method를 통해 digit을 구별한다.

-> Digit의 크기 비교를 통해 (.sorted()) 내림차순으로 정렬한다.

-> Collectors.joining()을 통해 다시 하나의 문자열로 합친다.

profile
Hello, Devs!

0개의 댓글