Maximize a given unsigned number number by swapping bits at it 's extreme positions. | Python 3 program to find maximum number by swapping extreme bits . ; Traverse bits from both extremes ; Obtaining i - th and j - th bits ; Swapping the bits if lesser significant is greater than higher significant bit and accordingly modifying the number ; Driver code
def findMax ( num ) : NEW_LINE INDENT num_copy = num NEW_LINE j = 4 * 8 - 1 ; NEW_LINE i = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT m = ( num_copy >> i ) & 1 NEW_LINE n = ( num_copy >> j ) & 1 NEW_LINE if ( m > n ) : NEW_LINE INDENT x = ( 1 << i 1 << j ) NEW_LINE num = num ^ x NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT num = 4 NEW_LINE print ( findMax ( num ) ) NEW_LINE DEDENT