Check if bitwise AND of any subset is power of two | CPP Program to check if Bitwise AND of any subset is power of two ; Check for power of 2 or not ; Check if there exist a subset whose bitwise AND is power of 2. ; if there is only one element in the set . ; Finding a number with all bit sets . ; check all the positions at which the bit is set . ; include all those elements whose i - th bit is set ; check for the set contains elements make a power of 2 or not ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int NUM_BITS = 32 ; bool isPowerOf2 ( int num ) { return ( num && ! ( num & ( num - 1 ) ) ) ; } bool checkSubsequence ( int arr [ ] , int n ) { if ( n == 1 ) return isPowerOf2 ( arr [ 0 ] ) ; int total = 0 ; for ( int i = 0 ; i < NUM_BITS ; i ++ ) total = total | ( 1 << i ) ; for ( int i = 0 ; i < NUM_BITS ; i ++ ) { int ans = total ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & ( 1 << i ) ) ans = ans & arr [ j ] ; } if ( isPowerOf2 ( ans ) ) return true ; } return false ; } int main ( ) { int arr [ ] = { 12 , 13 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkSubsequence ( arr , n ) ) printf ( " YES STRNEWLINE " ) ; else printf ( " NO STRNEWLINE " ) ; return 0 ; }