Question: You are given two numbers A and B. Write a program to count number of bits needed to be flipped to convert A to B.
Solution:
int bit_swaps_required( int a, int b ) { unsigned int count = 0; for( int c = a ^ b; c != 0; c = c >> 1 ) { count += c & 1; } return count; }
Read full article from Count number of bits to be flipped to convert A to B | GeeksforGeeks
Solution:
1. Calculate XOR of A and B.
a_xor_b = A ^ B
2. Count the set bits in the above calculated XOR result.
countSetBits(a_xor_b)
http://www.mytechinterviews.com/bit-swapsint bit_swaps_required( int a, int b ) { unsigned int count = 0; for( int c = a ^ b; c != 0; c = c >> 1 ) { count += c & 1; } return count; }
Read full article from Count number of bits to be flipped to convert A to B | GeeksforGeeks