Closest ( or Next ) smaller and greater numbers with same number of set bits | Main Function to find next smallest number bigger than n ; Compute c0 and c1 ; If there is no bigger number with the same no . of 1 's ; Driver Code ; input 1 ; input 2
def getNext ( n ) : NEW_LINE INDENT c = n NEW_LINE c0 = 0 NEW_LINE c1 = 0 NEW_LINE while ( ( ( c & 1 ) == 0 ) and ( c != 0 ) ) : NEW_LINE INDENT c0 = c0 + 1 NEW_LINE c >>= 1 NEW_LINE DEDENT while ( ( c & 1 ) == 1 ) : NEW_LINE INDENT c1 = c1 + 1 NEW_LINE c >>= 1 NEW_LINE DEDENT if ( c0 + c1 == 31 or c0 + c1 == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return n + ( 1 << c0 ) + ( 1 << ( c1 - 1 ) ) - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( getNext ( n ) ) NEW_LINE n = 8 NEW_LINE print ( getNext ( n ) ) NEW_LINE DEDENT