Count all pairs with given XOR in C++

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to find the number of pairs with the given XOR.

For this we will be provided with an array and a value. Our task is to find the number of pairs whose XOR is equal to the given value.

Example

#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;
}

Output

Count of pairs with given XOR = 1
Updated on 10-Feb-2020 11:07:13