Maximize the Expression | Bit Manipulation | Javascript 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
let MAX = 32 ; function maximizeExpression ( a , b ) { let result = a ; for ( let bit = MAX - 1 ; bit >= 0 ; bit -- ) { let bitOfD = 1 << bit ; let x = b & bitOfD ; if ( x == bitOfD ) { let y = result & bitOfD ; if ( y == 0 ) { result = result ^ bitOfD ; } } } return result ; } let a = 11 , b = 14 ; document . write ( maximizeExpression ( a , b ) ) ;