ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อหาจำนวนคู่ที่มี XOR ตามที่กำหนด
สำหรับเรื่องนี้ เราจะได้รับอาร์เรย์และค่า งานของเราคือหาจำนวนคู่ที่ XOR ของพวกเขาเท่ากับค่าที่กำหนด
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
// returning the number of pairs having XOR equal to given value
int count_pair(int arr[], int n, int x) {
int result = 0;
// managing with duplicate values
unordered_map<int, int> m;
for (int i = 0; i < n; i++) {
int curr_xor = x ^ arr[i];
if (m.find(curr_xor) != m.end())
result += m[curr_xor];
m[arr[i]]++;
}
return result;
}
int main() {
int arr[] = {2, 5, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 0;
cout << "Count of pairs with given XOR = " << count_pair(arr, n, x);
return 0;
}เอาต์พุต
Count of pairs with given XOR = 1