Number of pairs with Bitwise OR as Odd number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that counts the number of pairs in the given array whose bitwise OR is an odd number.

Let's see the steps to solve the problem.

  • Write two loops to get the pairs of the array.

  • Compute the bitwise OR between every pair.

  • Increment the count if the result is an odd number.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getOddPairsCount(int arr[], int n) {
   int count = 0;
   for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
         if ((arr[i] | arr[j]) % 2 != 0) {
            count++;
         }
      }
   }
   return count;
}
int main() {
   int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   int n = 10;
   cout << getOddPairsCount(arr, n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

35

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 08:31:52
Advertisements