Check if the binary representation of a number has equal number of 0 s and 1 s in blocks | Function to convert decimal to binary ; Count same bits in last block ; If n is 0 or it has all 1 s , then it is not considered to have equal number of 0 s and 1 s in blocks . ; Count same bits in all remaining blocks . ; Driver Code
def isEqualBlock ( n ) : NEW_LINE INDENT first_bit = n % 2 NEW_LINE first_count = 1 NEW_LINE n = n // 2 NEW_LINE while n % 2 == first_bit and n > 0 : NEW_LINE INDENT n = n // 2 NEW_LINE first_count += 1 NEW_LINE DEDENT if n == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT while n > 0 : NEW_LINE INDENT first_bit = n % 2 NEW_LINE curr_count = 1 NEW_LINE n = n // 2 NEW_LINE while n % 2 == first_bit : NEW_LINE INDENT n = n // 2 NEW_LINE curr_count += 1 NEW_LINE DEDENT if curr_count != first_count : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 51 NEW_LINE if isEqualBlock ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT