Find a number M < N such that difference between their XOR and AND is maximum | C ++ program for the above approach ; Function to flip all bits of N ; Finding most significant bit of N ; Calculating required number ; Return the answer ; Driver Code ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findM ( int N ) { int M = 0 ; int MSB = ( int ) log2 ( N ) ; for ( int i = 0 ; i < MSB ; i ++ ) { if ( ! ( N & ( 1 << i ) ) ) M += ( 1 << i ) ; } return M ; } int main ( ) { int N = 6 ; cout << findM ( N ) ; return 0 ; }