Given an array A of size N, the task is to count the number of pairs such that their XOR value has odd number of set bits in it.
Examples :
Input : arr[] = {1, 2, 3, 4, 5}, N = 5
Output : 6
Explanation :
The possible pairs are {1, 3}, {1, 5}, {2, 3}, {2, 5}, {3, 4}, {4, 5}
Input : arr[] = {1, 4, 9, 16, 25}, N=5
Output : 4
Approach :
The idea is to generate all possible pairs of the given array and check whether the XOR of the pair has an odd number of set bits. If it has odd number of set bits, count it, otherwise ignore it.
Implementation :
// Java Program for
// the above approach
class Main {
// Function to count the
// number of pairs with their
// XOR having odd number
// of set bits
static void countPairs(int a[], int n)
{
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int val = a[i] ^ a[j];
if (Integer.bitCount(val) % 2 != 0) {
count++;
}
}
}
System.out.println(count);
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 5 };
int N = arr.length;
countPairs(arr, N);
}
}
Time Complexity : O(N2)
Auxillary Space: O(1)