Count pairs with Bitwise XOR as ODD number in C++


We are given an integer array and the task is to count the total number of pairs that can be formed using the given array values such that the XOR operation on the pairs will result in an ODD value.

The truth table for XOR operation is given below

ABA XOR B
000
101
011
110

Input − int arr[] = {2, 8, 1, 5, 11}

Output − Count of pairs with Bitwise XOR as ODD number are − 6

Explanation

Explanation

a1a2a1 XOR a2
2810
213
257
2119
819
8513
8113
154
11110
51114

Approach used in the below program is as follows

  • Input an array of integer elements to form an pair

  • Calculate the size of an array pass the data to the function for further processing

  • Create a temporary variable count to store the pairs formed with XOR operation as an odd value.

  • Start loop FOR from i to 0 till the size of an array

  • Now calculate the odd value pairs in an array as count * (size - count)

  • Return the odd

  • Print the result

Example

 Live Demo

#include <iostream>
using namespace std;
//Count pairs with Bitwise XOR as ODD number
int XOR_Odd(int arr[], int size){
   int count = 0;
   for (int i = 0; i < size; i++){
      if (arr[i] % 2 == 0){
         count++;
      }
   }
   int odd = count * (size-count);
   return odd;
}
int main(){
   int arr[] = { 6, 1, 3, 4, 8, 9};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs with Bitwise XOR as ODD number are: "<<XOR_Odd(arr, size);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of pairs with Bitwise XOR as ODD number are: 9

Updated on: 31-Aug-2020

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements