Given an integer ‘x’, write a C function that returns true if binary representation of x is palindrome else return false.

For example a numbers with binary representation as 10..01 is palindrome and number with binary representation as 10..00 is not palindrome.

The idea is similar to checking a string is palindrome or not. We start from leftmost and rightmost bits and compare bits one by one. If we find a mismatch, then return false.

We strongly recommend that you click here and practice it, before moving on to the solution.

[ad type=”banner”]

Algorithm:
isPalindrome(x)
1) Find number of bits in x using sizeof() operator.
2) Initialize left and right positions as 1 and n respectively.
3) Do following while left ‘l’ is smaller than right ‘r’.
..…..a) If bit at position ‘l’ is not same as bit at position ‘r’, then return false.
..…..b) Increment ‘l’ and decrement ‘r’, i.e., do l++ and r–-.
4) If we reach here, it means we didn’t find a mismatching bit.

To find the bit at a given position, we can use the idea similar to this post. The expression “x & (1 << (k-1))” gives us non-zero value if bit at k’th position from right is set and gives a zero value if if k’th bit is not set.

Following is C++ implementation of the above algorithm.

[pastacode lang=”cpp” manual=”%23include%3Ciostream%3E%0Ausing%20namespace%20std%3B%0A%20%0A%2F%2F%20This%20function%20returns%20true%20if%20k’th%20bit%20in%20x%20is%20set%20(or%201).%0A%2F%2F%20For%20example%20if%20x%20(0010)%20is%202%20and%20k%20is%202%2C%20then%20it%20returns%20true%0Abool%20isKthBitSet(unsigned%20int%20x%2C%20unsigned%20int%20k)%0A%7B%0A%20%20%20%20return%20(x%20%26%20(1%20%3C%3C%20(k-1)))%3F%20true%3A%20false%3B%0A%7D%0A%20%0A%2F%2F%20This%20function%20returns%20true%20if%20binary%20representation%20of%20x%20is%0A%2F%2F%20palindrome.%20For%20example%20(1000…001)%20is%20paldindrome%0Abool%20isPalindrome(unsigned%20int%20x)%0A%7B%0A%20%20%20%20int%20l%20%3D%201%3B%20%2F%2F%20Initialize%20left%20position%0A%20%20%20%20int%20r%20%3D%20sizeof(unsigned%20int)*8%3B%20%2F%2F%20initialize%20right%20position%0A%20%0A%20%20%20%20%2F%2F%20One%20by%20one%20compare%20bits%0A%20%20%20%20while%20(l%20%3C%20r)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20if%20(isKthBitSet(x%2C%20l)%20!%3D%20isKthBitSet(x%2C%20r))%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20false%3B%0A%20%20%20%20%20%20%20%20l%2B%2B%3B%20%20%20%20%20r–%3B%0A%20%20%20%20%7D%0A%20%20%20%20return%20true%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20function%0Aint%20main()%0A%7B%0A%20%20%20%20unsigned%20int%20x%20%3D%201%3C%3C15%20%2B%201%3C%3C16%3B%0A%20%20%20%20cout%20%3C%3C%20isPalindrome(x)%20%3C%3C%20endl%3B%0A%20%20%20%20x%20%3D%201%3C%3C31%20%2B%201%3B%0A%20%20%20%20cout%20%3C%3C%20isPalindrome(x)%20%3C%3C%20endl%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C++ Programming” highlight=”” provider=”manual”/] [ad type=”banner”]

Output:

1
1

Categorized in: