Count of pairs whose bitwise AND is a power of 2 | C ++ program for the above approach ; Function to check if x is power of 2 ; Returns true if x is a power of 2 ; Function to return the number of valid pairs ; Iterate for all possible pairs ; Bitwise and value of the pair is passed ; Return the final count ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int x ) { return x && ( ! ( x & ( x - 1 ) ) ) ; } int count ( int arr [ ] , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( check ( arr [ i ] & arr [ j ] ) ) cnt ++ ; } } return cnt ; } int main ( ) { int arr [ ] = { 6 , 4 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << count ( arr , n ) ; return 0 ; }