The best programs are written so that computing machines can perform
them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist
who works with traditional aesthetic and literary forms as well as mathematical concepts, to
communicate the way that an algorithm works and to convince a reader that the results will be correct.
― Donald E. Knuth

Problem :-
Find the number of bits which are to be flipped to convert one integer to another.
For e.g, consider integers 11 ( 1011 ) & 5 ( 0101 ).
We see a mismatch in 3 bit positions. So, no. of bits to be flipped = 3.

Solution :-
Suppose the given integers are x & y.
Logic is to get XOR of 'x' & 'y'[ z = x XOR y ] &
count the number of set bits in 'z'.
Please note that XOR of two bits would be '1' if they do not match.

#include<iostream>using namespace std;
// count the no. of set bits in a positive integerunsigned int countSetBits(unsigned int num) {
unsigned int count = 0;
while (num) {
// bitwise AND operation to check if the
// leftmost bit is set or not
// if set, increment the count
count += num & 1;
// left shift the nm by one position
num >>= 1;
}
return count;
}
// get the no. of bits to be flipped to convert 'a' to 'b'unsigned int getNoBitsFlipped(int a, int b) {
// xor of 'a' & 'b' will have set bits at those
// places where bits of 'a' and 'b' differsunsigned int k = a ^ b;
return countSetBits(k);
}
// mainint main() {
int a = 41; // 101001int b = 28; // 011100int flip_bits = getNoBitsFlipped(a,b);
cout<<"\nNo. of bits to be flipped :: "<<flip_bits;
cout<<endl;
return 0;
}

#include<iostream>using namespace std;
// count the no. of set bits in a positive integerunsigned int countSetBits(unsigned int num) {
unsigned int count = 0;
while (num) {
// bitwise AND operation to check if the
// leftmost bit is set or not
// if set, increment the count
count += num & 1;
// left shift the nm by one position
num >>= 1;
}
return count;
}
// get the no. of bits to be flipped to convert 'a' to 'b'unsigned int getNoBitsFlipped(int a, int b) {
// xor of 'a' & 'b' will have set bits at those
// places where bits of 'a' and 'b' differsunsigned int k = a ^ b;
return countSetBits(k);
}
// mainint main() {
int a = 41; // 101001int b = 28; // 011100int flip_bits = getNoBitsFlipped(a,b);
cout<<"\nNo. of bits to be flipped :: "<<flip_bits;
cout<<endl;
return 0;
}