이 튜토리얼에서는 K 비트가 다른 배열의 쌍의 수를 찾는 프로그램에 대해 논의할 것입니다.
이를 위해 배열과 정수 K가 제공됩니다. 우리의 임무는 이진 표현에서 K 비트만큼 다른 쌍의 수를 찾는 것입니다.
예시
#include <bits/stdc++.h>
using namespace std;
//counting number of bits in
//binary representation
int count_bit(int n){
int count = 0;
while (n) {
if (n & 1)
++count;
n >>= 1;
}
return count;
}
//counting the number of pairs
long long count_pair(int arr[], int n, int k) {
long long ans = 0;
for (int i = 0; i < n-1; ++i) {
for (int j = i + 1; j < n; ++j) {
int xoredNum = arr[i] ^ arr[j];
if (k == count_bit(xoredNum))
++ans;
}
}
return ans;
}
int main() {
int k = 2;
int arr[] = {2, 4, 1, 3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Total pairs for k = " << k << " are " << count_pair(arr, n, k) << "\n";
return 0;
} 출력
5