Find a number M < N such that difference between their XOR and AND is maximum | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } int main ( ) { int N = 6 ; cout << getMaxDifference ( N ) ; return 0 ; }