How to Count number of bits to be flipped to convert A to B ?

Answer : Write the program to count number of bits needed to be flipped…

How to Count number of bits to be flipped to convert A to B ?

  • Write the program to count number of bits needed to be flipped to convert ‘a’ to ‘b’. For Example given two numbers a = 6 and b = 12; then the output is 2
    • Binary representation of a is 00000110
    • Binary representation of b is 00001100
    • We need to flip highlighted two bits in a
    • To make it b.

Explanation

  • Calculate XOR of A and B.
a_xor_b = A ^ B
  • Count the set bits in the above Calculated XOR result.
CountSetBits(a_xor_b)

Sample Code in C#

[pastacode lang=”c” manual=”%2F%20Count%20number%20of%20bits%20to%20be%20%0A%2F%2F%20flipped%20to%20convert%20A%20into%20B%20%0Ausing%20System%3B%20%0A%0Apublic%20class%20Count%20%7B%20%0A%09%0A%09%2F%2F%20Function%20that%20count%20set%20bits%20%0A%09public%20static%20int%20countSetBits(int%20n)%20%0A%09%7B%20%0A%09%09int%20count%20%3D%200%3B%20%0A%09%09while%20(n%20!%3D%200)%20%7B%20%0A%09%09%09count%20%2B%3D%20n%20%26%201%3B%20%0A%09%09%09n%20%3E%3E%3D%201%3B%20%0A%09%09%7D%20%0A%09%09return%20count%3B%20%0A%09%7D%20%0A%0A%09%2F%2F%20Function%20that%20return%20%0A%09%2F%2F%20count%20of%20flipped%20number%20%0A%09public%20static%20int%20FlippedCount(int%20a%2C%20int%20b)%20%0A%09%7B%20%0A%09%2F%2F%20Return%20count%20of%20set%20%0A%09%2F%2F%20bits%20in%20a%20XOR%20b%20%0A%09%09return%20countSetBits(a%20%5E%20b)%3B%20%0A%09%7D%20%0A%09%0A%09%2F%2F%20Driver%20code%20%0A%09public%20static%20void%20Main()%20%0A%09%7B%20%0A%09%09int%20a%20%3D%2017%3B%20%0A%09%09int%20b%20%3D%2055%3B%20%0A%09%09Console.WriteLine(FlippedCount(a%2C%20b))%3B%20%0A%09%7D%20%0A%7D%20%0A%0A%2F%2F%20This%20code%20is%20contributed%20by%20vt_m.%20″ message=”” highlight=”” provider=”manual”/]

Output

3
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like