Check whether bits are in alternate pattern in the given range | Set | 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
' NEW_LINE def isKthBitSet ( n , k ) : NEW_LINE INDENT if ( ( n >> ( k - 1 ) ) & 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT ' NEW_LINE def setKthBit ( n , k ) : NEW_LINE INDENT return ( ( 1 << ( k - 1 ) ) n ) NEW_LINE DEDENT ' NEW_LINE def allBitsAreSet ( n ) : NEW_LINE INDENT if ( ( ( n + 1 ) & n ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def bitsAreInAltOrder ( n ) : NEW_LINE INDENT num = n ^ ( n >> 1 ) NEW_LINE DEDENT ' NEW_LINE INDENT return allBitsAreSet ( num ) NEW_LINE DEDENT def bitsAreInAltPatrnInGivenRange ( n , l , r ) : NEW_LINE INDENT if ( isKthBitSet ( n , r ) ) : NEW_LINE INDENT num = n NEW_LINE left_shift = r NEW_LINE DEDENT else : NEW_LINE INDENT num = setKthBit ( n , ( r + 1 ) ) NEW_LINE left_shift = r + 1 NEW_LINE DEDENT num = num & ( ( 1 << left_shift ) - 1 ) NEW_LINE num = num >> ( l - 1 ) NEW_LINE return bitsAreInAltOrder ( num ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 18 NEW_LINE l = 1 NEW_LINE r = 3 NEW_LINE if ( bitsAreInAltPatrnInGivenRange ( n , l , r ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT