Last Updated: 21 Nov, 2021

Number of Flips

Easy
Asked in companies
Info Edge India (Naukri.com)WalmartD.E.Shaw

Problem statement

Ninja is learning the binary representation of the numbers. He wanted to practice the topic, so he picked a question. The problem statement says, two numbers, β€˜A’ and β€˜B’ are given. Find the number of bits of β€˜B’ that should be flipped to convert it into β€˜A’.Can you help Ninja to solve this problem?

You are given two integers, β€˜A’ and β€˜B’.Find the number of bits of β€˜B’ that should be flipped to convert it into β€˜A’.

For Example
If β€˜A’ is 13(1101) and β€˜B’ is 7(0111), The number of bits that should be flipped is 2(0111). 
Input Format:
The first line of the input contains an integer, 'T,’ denoting the number of test cases.

The first line of each test case contains two integers, β€˜A’ and β€˜B’.
Output Format:
For each test case, print β€˜an integer corresponding to the minimum number of swaps required.

Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= β€˜A’,’B’ <= 10^9.

Time limit: 1 sec

Approaches

01 Approach

In this approach, we will simply iterate through all the bits of β€˜A’ and β€˜B’ and count the number of bits that are not matching, as if we just change these mismatched bits, we will find the number of bits that should be flipped.

At last, we will return β€˜ANS’ storing the number of flips required. 

 

Algorithm:

  • Declare β€˜ANS’ to store the required answer.
  • While β€˜A’ is greater than 0 or β€˜B’ is greater than 0:
    • Set bit_A as A%2.
    • Set bit_B as B%2.
    • If bit_A is not equal to  bit_B:
      • Mismatched bit found.
      • Increase β€˜ANS’ as β€˜ANS’+1.
    • Set β€˜A’ as β€˜A’/2.
    • Set β€˜B’ as β€˜B’/2.
  • Return β€˜ANS’.

02 Approach

In this approach, we will first take the bitwise XOR of β€˜A’ and β€˜B’ in a variable β€˜C’.Now, the β€˜C’ will contain only those bit sets that are mismatching in β€˜A’ and β€˜B’ for the following property of XOR:

    0 XOR 0 is 0.

    0 XOR 1 is 1.

    1 XOR 0 is 1.

    1 XOR 1 is 0.

We will simply count the number of set bits in β€˜C’ and return the required number.

   

Algorithm:

  • Set β€˜C’ as β€˜A’ XOR β€˜B’.
  • Declare β€˜ANS’ to store the number of set bits of β€˜C’.
  • Set β€˜ANS’ as 0.
  • While β€˜C’ >0, do the following:
    • If β€˜C’ % 2 == 1:
      • Set β€˜ANS’ as β€˜ANS’+1.
    • Set β€˜C’ as β€˜C’/2.
  • Return β€˜ANS’.