Maximize the Expression | Bit Manipulation | Python3 implementation of the approach ; Function to return the value of the maximized expression ; int can have 32 bits ; Consider the ith bit of D to be 1 ; Calculate the value of ( B AND bitOfD ) ; Check if bitOfD satisfies ( B AND D = D ) ; Check if bitOfD can maximize ( A XOR D ) ; Note that we do not need to consider ith bit of D to be 0 because if above condition are not satisfied then value of result will not change which is similar to considering bitOfD = 0 as result XOR 0 = result ; Driver code
MAX = 32 NEW_LINE def maximizeExpression ( a , b ) : NEW_LINE INDENT result = a NEW_LINE for bit in range ( MAX - 1 , - 1 , - 1 ) : NEW_LINE INDENT bitOfD = 1 << bit NEW_LINE x = b & bitOfD NEW_LINE if ( x == bitOfD ) : NEW_LINE INDENT y = result & bitOfD NEW_LINE if ( y == 0 ) : NEW_LINE INDENT result = result ^ bitOfD NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT a = 11 NEW_LINE b = 14 NEW_LINE print ( maximizeExpression ( a , b ) ) NEW_LINE