Minimum bit swaps between given numbers to make their Bitwise OR equal to Bitwise AND | 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 ; Input ; Function call to compute the result
function countSetBits ( n ) { let count = 0 ; while ( n ) { n = n & ( n - 1 ) ; count ++ ; } return count ; } function minOperations ( A , B ) { let cnt1 = 0 , cnt2 = 0 ; cnt1 += countSetBits ( A ) ; cnt2 += countSetBits ( B ) ; if ( ( cnt1 + cnt2 ) % 2 != 0 ) return - 1 ; let oneZero = 0 , zeroOne = 0 ; let ans = 0 ; for ( let i = 0 ; i < Math . max ( cnt1 , cnt2 ) ; i ++ ) { let bitpos = 1 << i ; if ( ( ! ( bitpos & A ) ) && ( bitpos & B ) ) zeroOne ++ ; if ( ( bitpos & A ) && ( ! ( bitpos & B ) ) ) oneZero ++ ; } ans = parseInt ( zeroOne / 2 ) + parseInt ( oneZero / 2 ) ; if ( zeroOne % 2 != 0 ) ans += 2 ; return ans ; } let A = 27 , B = 5 ; document . write ( minOperations ( A , B ) ) ;