happy coding

[java] 구름톤 5일차. 이진수 정렬 본문

coding study

[java] 구름톤 5일차. 이진수 정렬

yeoonii 2023. 8. 18. 21:06

문제

N개의 10진수 정수가 주어진다. 플레이어에게 정수를 그냥 정렬하는 것은 너무 쉽기 때문에, 아래 기준에 따라 정수를 정렬하기로 한다.
1. 10진수 정수를 2진수로 나타냈을 때, 2진수에 포함된 1의 개수를 기준으로 내림차순 정렬한다.
2. 1의 개수가 같다면, 원래 10진수를 기준으로 내림차순 정렬한다.
플레이어가 정수를 잘 정렬했을 때, 앞에서 K번째에 위치한 수는 어떤 수가 될지 구해보자.

 

입력

첫째 줄에 주어지는 정수의 수 N과 플레이어가 찾으려는 정수의 위치 K가 공백을 두고 주어진다.
둘째 줄에 정수 a1, ... , aN이 공백을 두고 주어진다.
- 1 <= N <= 500000
- 1 <= K <= N
- 1 < = ai <= 2^20

 

출력

기준에 따라 정렬된 정수 중, 앞에서 K번째에 위치한 수를 출력한다.


import java.io.*;
import java.util.*;

class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");

        int N = Integer.parseInt(st.nextToken());
        int K = Integer.parseInt(st.nextToken());

        Integer[] array = new Integer[N]; // int[] 대신 Integer[]로 변경
        StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
        for (int i = 0; i < N; i++) {
            array[i] = Integer.parseInt(st1.nextToken());
        }

        Arrays.sort(array, (a, b) -> {
            int countA = countOnesInBinary(a);
            int countB = countOnesInBinary(b);
            return countA == countB ? Integer.compare(b, a) : Integer.compare(countB, countA);
        });

        System.out.println(array[K - 1]);
    }

    public static int countOnesInBinary(int binary) {
        int count = 0;
        while (binary > 0) {
            count += binary & 1;
            binary >>= 1;
        }
        return count;
    }
}

돌아돌아갔다. 그리고 Interger로 해야 오류가 안나는걸 알았다.

Comments