Check if a number has same number of set and unset bits | Function to check if a number has same setbits and unset bits ; iterate for all bits of a number ; if set ; if unset ; right shift number by 1 ; is number of set bits are equal to unset bits ; Driver Code ; function to check
def checkSame ( n ) : NEW_LINE INDENT set , unset = 0 , 0 NEW_LINE while ( n ) : NEW_LINE INDENT if ( n and 1 ) : NEW_LINE INDENT set + 1 NEW_LINE DEDENT else : NEW_LINE INDENT unset += 1 NEW_LINE DEDENT n = n >> 1 NEW_LINE DEDENT if ( set == unset ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE if ( checkSame ( n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT