Problem Statement:
You are given a number n, you need to check if its binary representation is a palindrome or not.
Example:
Input : 9
Output: yes
9 in binary is 1001
Solution Explanation:
Solution is very simple.
You need to reverse the bits of the number, then check if the number is equal to the given number. If yes, return true.
To reverse the bits of the given number, use below steps:
1. Take a variable “res” to store the reverse bits.
2. For every new bit, left shoft the res to store the new bit.
3. When a set bit is encountered, then set the rightmost bit of the result. (res |= 1).
4. Traverse each bit of the number using right shift operator ( num >>= 1)
Time Complexity: O(num)
Space Complexity: O(1)
Code Solution
#include <bits/stdc++.h>
using namespace std;
unsigned int reverseBits(unsigned int n)
{
int res = 0;
while (n > 0) {
res <<= 1;
if (n & 1 == 1)
res ^= 1;
n >>= 1;
}
return res;
}
bool checkIsPalindrome(int n)
{
int rev = reverseBits(n);
return (n == rev);
}
int main()
{
int n = 9;
if (checkIsPalindrome(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Output
Yes