Check if the binary representation of a positive number is palindrome or not.

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

Practice this problem

 
The idea is simple – construct a reverse of the binary representation of n and return true if it is the same as n. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

9 is a palindrome

Java


Download  Run Code

Output:

9 is a palindrome

Python


Download  Run Code

Output:

9 is a palindrome

 
Also See:

Bit Hacks – Part 1 (Basic)
Bit Hacks – Part 2 (Playing with k’th bit)
Bit Hacks – Part 3 (Playing with the rightmost set bit of a number)
Bit Hacks – Part 4 (Playing with letters of the English alphabet)
Bit Hacks – Part 5 (Find the absolute value of an integer without branching)

 
Suggested Read:

https://graphics.stanford.edu/~seander/bithacks.html