Check whether bits are in alternate pattern in the given range | Set | Java implementation to check whether bits are in alternate pattern in the given range ; function to check whether rightmost kth bit is set or not in ' n ' ; function to set the rightmost kth bit in ' n ' ; kth bit of n is being set by this operation ; function to check if all the bits are set or not in the binary representation of ' n ' ; if true , then all bits are set ; else all bits are not set ; function to check if a number has bits in alternate pattern ; to check if all bits are set in ' num ' ; function to check whether bits are in alternate pattern in the given range ; preparing a number ' num ' and ' left _ shift ' which can be further used for the check of alternate pattern in the given range ; unset all the bits which are left to the rth bit of ( r + 1 ) th bit ; right shift ' num ' by ( l - 1 ) bits ; Driver code
class GFG { static boolean isKthBitSet ( int n , int k ) { if ( ( n >> ( k - 1 ) ) == 1 ) return true ; return false ; } static int setKthBit ( int n , int k ) { return ( ( 1 << ( k - 1 ) ) n ) ; } static boolean allBitsAreSet ( int n ) { if ( ( ( n + 1 ) & n ) == 0 ) return true ; return false ; } static boolean bitsAreInAltOrder ( int n ) { int num = n ^ ( n >> 1 ) ; return allBitsAreSet ( num ) ; } static boolean bitsAreInAltPatrnInGivenRange ( int n , int l , int r ) { int num , left_shift ; if ( isKthBitSet ( n , r ) ) { num = n ; left_shift = r ; } else { num = setKthBit ( n , ( r + 1 ) ) ; left_shift = r + 1 ; } num = num & ( ( 1 << left_shift ) - 1 ) ; num = num >> ( l - 1 ) ; return bitsAreInAltOrder ( num ) ; } public static void main ( String [ ] args ) { int n = 18 ; int l = 1 , r = 3 ; if ( bitsAreInAltPatrnInGivenRange ( n , l , r ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }