Find a number M < N such that difference between their XOR and AND is maximum | Java program for the above approach ; Function to return M < N such that N ^ M - N & M is maximum ; Initialize variables ; Iterate for all values < N ; Find the difference between Bitwise XOR and AND ; Check if new difference is greater than previous maximum ; Update variables ; Return the answer ; Driver Code ; Given Number N ; Function Call
class GFG { static int getMaxDifference ( int N ) { int M = - 1 ; int maxDiff = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int diff = ( N ^ i ) - ( N & i ) ; if ( diff >= maxDiff ) { maxDiff = diff ; M = i ; } } return M ; } public static void main ( String [ ] args ) { int N = 6 ; System . out . print ( getMaxDifference ( N ) ) ; } }