Find closest integer with the same weight | Python3 implementation of the approach ; Function to return the number closest to x which has equal number of set bits as x ; Loop for each bit in x and compare with the next bit ; Driver code
NumUnsignBits = 64 ; NEW_LINE def findNum ( x ) : NEW_LINE INDENT for i in range ( NumUnsignBits - 1 ) : NEW_LINE INDENT if ( ( ( x >> i ) & 1 ) != ( ( x >> ( i + 1 ) ) & 1 ) ) : NEW_LINE INDENT x ^= ( 1 << i ) | ( 1 << ( i + 1 ) ) ; NEW_LINE return x ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 92 ; NEW_LINE print ( findNum ( n ) ) ; NEW_LINE DEDENT