Count number of bits to be flipped to convert A to B. OR
Find number of Bit swaps required to convert one integer to another OR
Given two integers A & B. Determine how many bits required to convert A to B.
Given two number A and B, Write an algorithm to count the number of bit flips required to convert A to B
Let's see what is the input and expected output for better understanding,
Case 1:
Input A: 6 (Binary equivalent of 6: 0 1 1 0 )
Input B: 8 (Binary equivalent of 8: 1 0 0 0 )
Output: Number of bits that need to be changed in A to convert it to B is : 3
Explanation: (From Right, For number 6,
Bit at position 0 is 0, which is same in both number,
Bit at position 1 is 1, which needs to be unset to match it to number B,
Bit at position 2 is 1, which needs to be unset to match it to number B,
Bit at position 3 is 0, which needs to be set to match it to number B)
Case 2:
Input A: 9 (Binary equivalent of 9: 0 1 0 0 )
Input B: 2 (Binary equivalent of 2: 0 0 1 0 )
Output: Number of bits that need to be changed in A to convert it to B is : 2
Explanation: (From Right, For number 9,
Bit at position 0 is 0, which is same in both number,
Bit at position 1 is 0, which needs to be set to match it to number B,
Bit at position 2 is 1, which needs to be unset to match it to number B,
Bit at position 3 is 0, which is same in both number)