计算C ++中具有给定XOR的所有对
在本教程中,我们将讨论一个程序来查找具有给定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
热门推荐
10 简短的祝福语12字
11 弟弟生日祝福语简短的话
12 比赛结束花束祝福语简短
13 老哥出门祝福语简短语
14 分别祝福语简短情侣短句
15 十月简短祝福语
16 祝美术老师祝福语简短
17 女生成年祝福语简短
18 春季祝福语女生文案简短