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 ; Driver code ; Input ; Function call to compute the result
def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def minOperations ( A , B ) : NEW_LINE INDENT cnt1 = 0 NEW_LINE cnt2 = 0 NEW_LINE cnt1 += countSetBits ( A ) NEW_LINE cnt2 += countSetBits ( B ) NEW_LINE if ( ( cnt1 + cnt2 ) % 2 != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT oneZero = 0 NEW_LINE zeroOne = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( max ( cnt1 , cnt2 ) ) : NEW_LINE INDENT bitpos = 1 << i NEW_LINE if ( ( not ( bitpos & A ) ) and ( bitpos & B ) ) : NEW_LINE INDENT zeroOne += 1 NEW_LINE DEDENT if ( ( bitpos & A ) and ( not ( bitpos & B ) ) ) : NEW_LINE INDENT oneZero += 1 NEW_LINE DEDENT DEDENT ans = ( zeroOne // 2 ) + ( oneZero // 2 ) NEW_LINE if ( zeroOne % 2 != 0 ) : NEW_LINE INDENT ans += 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 27 NEW_LINE B = 5 NEW_LINE print ( minOperations ( A , B ) ) NEW_LINE DEDENT