在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP