Check if binary representation of a number is palindrome | GeeksforGeeks
Given an integer ‘x’, write a C function that returns true if binary representation of x is palindrome else return false.
http://codesam.blogspot.com/2011/06/check-if-integers-bit-representation-is.html
Thus, in order to know if it is a palindrome or not, we just have to check if the number's value is still the same when we read the number's bits backward (right to left). For example, 5 is 101 and when we read its bits from right to left, which is 101, the result is still 5.
This may cause overflow.
Given an integer ‘x’, write a C function that returns true if binary representation of x is palindrome else 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.
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.
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.
// This function returns true if binary representation of x is
// palindrome. For example (1000...001) is paldindrome
bool
isPalindrome(unsigned
int
x)
{
int
l = 1;
// Initialize left position
int
r =
sizeof
(unsigned
int
)*8;
// initialize right position
// One by one compare bits
while
(l < r)
{
if
(isKthBitSet(x, l) != isKthBitSet(x, r))
return
false
;
l++; r--;
}
return
true
;
}
// This function returns true if k'th bit in x is set (or 1).
// For example if x (0010) is 2 and k is 2, then it returns true
bool
isKthBitSet(unsigned
int
x, unsigned
int
k)
{
return
(x & (1 << (k-1)))?
true
:
false
;
}
Thus, in order to know if it is a palindrome or not, we just have to check if the number's value is still the same when we read the number's bits backward (right to left). For example, 5 is 101 and when we read its bits from right to left, which is 101, the result is still 5.
This may cause overflow.
function bIsIntPalindrome(nInputNum) { if (nInputNum === 'undefined' || nInputNum === null || nInputNum < 0) return false; var nInputNumCopy = nInputNum; var nResultNum = 0; while (nInputNumCopy > 0) { nResultNum <<= 1; if (nInputNumCopy & 1) { nResultNum |=1; } nInputNumCopy >>= 1; } if (nInputNum == nResultNum) return true; return false; }Read full article from Check if binary representation of a number is palindrome | GeeksforGeeks