# Bit Hacks – Part 6 (Random Problems)

In this post, we will discuss few unrelated problems that can be solved using bit manipulation hacks.

## 1. Find number of bits needed to be flipped to convert given integer to another

The idea is to take XOR of given two integers. After calculating the XOR, the problem will reduces to counting set bits in the XOR output.

## C++

Output:

65 in binary is 01000001
80 in binary is 01010000

The number of bits flipped is 2

## 2. Check if binary representation of a number is palindrome or not

For example, 101, 11, 11011, 1001001 are palindromes. 100, 110, 1011, etc are not palindromes.

Well, there is no one-liner trick to solve this one. 😛

The idea is to construct reverse of binary representation of n and return true if it is same as n.

## C++

Output:

9 is Palindrome

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Subscribe
Notify of
Guest
Tanmay Jha

Can someone please explain how the binary number is being reversed.
————————————————————
unsigned rev = 0;
unsigned k = n;

while (k)
{
// add rightmost bit to rev
rev = (rev <> 1; // drop last bit
cout<<"k val is "<<bitset(k)<<endl;
cout<<"rev val is "<<{bitset(rev)<<endl;
}

————————————————————

Output if n=9

k val is 00000100
rev val is 00000001
k val is 00000010
rev val is 00000010
k val is 00000001
rev val is 00000100
k val is 00000000
rev val is 00001001
9 is Palindrome

————————————————————

As far as I know, only first expression is executed if it is true for "|" condition statement. So, here rev<<1 will be false only for first case but not for others. Therefore how does rev get 1 in the end for last condition because (k&1) won't be executed. Only left shift will be executed right?