Check if all the set bits of the binary representation of N are at least K places away | Python3 program to check if all the set bits of the binary representation of N are at least K places away . ; Initialize check and count with 0 ; The i - th bit is a set bit ; This is the first set bit so , start calculating all the distances between consecutive bits from here ; If count is less than K return false ; Adding the count as the number of zeroes increase between set bits ; Driver code
def CheckBits ( N , K ) : NEW_LINE INDENT check = 0 NEW_LINE count = 0 NEW_LINE for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT if ( ( 1 << i ) & N ) : NEW_LINE INDENT if ( check == 0 ) : NEW_LINE INDENT check = 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( count < K ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT count = 0 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE K = 1 NEW_LINE if ( CheckBits ( N , K ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT