Minimum bit swaps between given numbers to make their Bitwise OR equal to Bitwise AND | C ++ implementation of the above approach ; Function for counting number of set bit ; Function to return the count of minimum operations required ; cnt to count the number of bits set in A and in B ; if odd numbers of total set bits ; one_zero = 1 in A and 0 in B at ith bit similarly for zero_one ; When bitpos is set in B , unset in B ; When bitpos is set in A , unset in B ; number of moves is half of number pairs of each group ; odd number pairs ; Driver code ; Input ; Function call to compute the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { int count = 0 ; while ( n ) { n = n & ( n - 1 ) ; count ++ ; } return count ; } int minOperations ( int A , int B ) { int cnt1 = 0 , cnt2 = 0 ; cnt1 += countSetBits ( A ) ; cnt2 += countSetBits ( B ) ; if ( ( cnt1 + cnt2 ) % 2 != 0 ) return -1 ; int oneZero = 0 , zeroOne = 0 ; int ans = 0 ; for ( int i = 0 ; i < max ( cnt1 , cnt2 ) ; i ++ ) { int bitpos = 1 << i ; if ( ( ! ( bitpos & A ) ) && ( bitpos & B ) ) zeroOne ++ ; if ( ( bitpos & A ) && ( ! ( bitpos & B ) ) ) oneZero ++ ; } ans = ( zeroOne / 2 ) + ( oneZero / 2 ) ; if ( zeroOne % 2 != 0 ) ans += 2 ; return ans ; } int main ( ) { int A = 27 , B = 5 ; cout << minOperations ( A , B ) ; return 0 ; }