計算在 C++ 中位數差別為 K 位的陣列中所有對的個數
在本教程中,我們將討論一個程式,以找出陣列中有多少對的二進位制表示差異為 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP