https://9oormthonchallenge.oopy.io/
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
const int *first = (const int *)a;
const int *second = (const int *)b;
if (first[1] < second[1])
return 1;
else if (first[1] > second[1])
return -1;
else if (first[0] < second[0])
return 1;
else if (first[0] > second[0])
return -1;
else
return 0;
}
int n, k, arr[1111111];
int main() {
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++) {
int a;
scanf("%d", &a);
arr[i * 2] = a;
int count = 0;
while (a) {
a &= (a - 1);
count++;
}
arr[i * 2 + 1] = count;
}
qsort(arr, n, sizeof(int) * 2, compare);
printf("%d\n", arr[(k - 1) * 2]);
return 0;
}
2진수로 나타냈을 때 1의 개수를 구하는 법은 이번에 새로 알게 되었다.
int a = 7
int count = 0;
while (a) {
if (a & 1) count++;
a >>= 1;
}
원래 이렇게 작성했는데, 더 빠른 방법이 있었다.
int a = 7
int count = 0;
while (a) {
a &= (a - 1);
count++;
}
이렇게 하면, a &= (a - 1)
를 실행할 때, 1의 개수가 하나씩 줄어든다. 즉 while loop를 count만큼만 돌고 나와서 1의 개수를 구할 때 더 빠르다.