C++ program to check if binary representation of a number is palindrome
For a non-negative number x, print Yes if the binary representation of x is a palindrome else print No in C++. The binary representation of a number with leading 0’s will not be considered for checking palindrome.
What are a binary representation and a palindrome?
A binary number is a number that uses only 0 and 1 in the base 2 numeral system and a palindrome is a string, phrase, or a number that remains the same even if its digits or characters are reversed.
Algorithm:
1) The first step is to make a function check_palindrome in which first we find the number of bits in x using sizeof()
and set left positions as 1 and right positions as n.
2)The next step is, while left ‘x’ is smaller than right ‘y’:
->Return false if the bit at x is not equal to y and keep incrementing x and decrementing y.
3) If we come to this step it means there was no mismatching bit.
The expression “x &(1<<(a-1))” gives a value zero if the a’th bit from the right is not set and non zero value if it is set.
Example:
If the binary representation of a number is 1001, then it is a palindrome and if it is 1100, then it is not a palindrome.
Program to check if the binary representation of a number is a palindrome in C++
#include<bits/stdc++.h> using namespace std; // function returns true if a'th bit is set // and false if it is not set bool bit_set(int x,int a) { return (x & (1<<(a-1))) ? true : false; } // function returns true if p is a palindrome // and false if it is not bool check_palindrome(int p) { int x=1; // set the left position int y=sizeof(int)*8; // set the right position //comparing bits while(x<y) { if(bit_set(p,x)!=bit_set(p,y)) return false; x++; y--; } return true; } int main() { int p= 1 <<15+1<<16; cout<<check_palindrome(p)<<endl; p=1 <<31+1; cout<<check_palindrome(p)<<endl; }
Output: 1 1
Leave a Reply