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.
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 the implementation of the above algorithm.
This article is contributed by Saurabh Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Check if actual binary representation of a number is palindrome
- Find the n-th number whose binary representation is a palindrome
- Check if binary representation of a given number and its complement are anagram
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Check if all the set bits of the binary representation of N are at least K places away
- Binary representation of next number
- Binary representation of a given number
- Count number of trailing zeros in Binary representation of a number using Bitset
- Binary representation of previous number
- Next greater number than N with exactly one bit different in binary representation of N
- Largest number with binary representation is m 1's and m-1 0's
- Number of leading zeros in binary representation of a given number
- Occurrences of a pattern in binary representation of a number
- Prime Number of Set Bits in Binary Representation | Set 1
- Prime Number of Set Bits in Binary Representation | Set 2
- Smallest multiple of N with exactly N digits in its Binary number representation
- Find the number obtained after concatenation of binary representation of M and N
- C program to count zeros and ones in binary representation of a number
- Sum of decimal equivalent of all possible pairs of Binary representation of a Number
- Number of mismatching bits in the binary representation of two integers