21.08.24 기록

최대 1 분 소요

백준 알고리즘 1427 풀이

🎆나의 풀이(메모리 14.2MB, 시간 132ms로 통과)

-이전에 풀었던 정렬 로직과 비슷한 방법으로 풀이했다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

        int[] check = new int[10];
        for(int i = 0; i < N.length(); i++) {
            check[N.charAt(i)-48]++;
        }

        StringBuilder sb = new StringBuilder();
        for(int i = (check.length-1); i >= 0; i--) {
            while(check[i] > 0) {
                sb.append(i);
                check[i]--;
            }
        }
        System.out.println(sb);
    }
}


🎆해설(메모리 14.2MB, 시간 28ms로 통과)

-charAt() 대신 수학연산(N%10)을 사용하여 풀이할 수도 있다.
-아래는 BufferedReader가 아닌 InputStream을 사용한 코드이다.

import java.io.IOException;
import java.io.InputStream;

public class B1427 {
    public static void main(String[] args) throws IOException {
        InputStream is = System.in;
        int[] counting = new int[10];

        int c;
        while((c = is.read()) != '\n') {
            counting[c - '0']++;
        }

        StringBuilder sb = new StringBuilder();
        for(int i = 9; i >= 0; i--) {
            while(counting[i]-- > 0) {
                sb.append(i);
            }
        }
        System.out.println(sb);
    }
}

카테고리:

업데이트: