Check if bitwise AND of any subset is power of two | Java 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 Code
import java . io . * ; import java . util . * ; public class GFG { static int NUM_BITS = 32 ; static boolean isPowerOf2 ( int num ) { if ( num != 0 && ( num & ( num - 1 ) ) == 0 ) return true ; return false ; } static boolean 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 ++ ) { int p = arr [ j ] & ( 1 << i ) ; if ( p == 0 ) ans = ans & arr [ j ] ; } if ( isPowerOf2 ( ans ) ) return true ; } return false ; } public static void main ( String args [ ] ) { int [ ] arr = { 12 , 13 , 7 } ; int n = arr . length ; if ( checkSubsequence ( arr , n ) ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } }