1. Determine whether bit-wise representation of the integer is a palindrome. Consider all bits including leftmost zeros.
The idea is simple: use two pointers, left and right, first left pointer points to the left most bit, right pointer points to right most bit, check whether these 2 bit values are same, loop all 32 bit.
This means 5 = 101b is also a palindrome.
The idea comes from this link, I just converted it to java code:
Fun with Bitwise Operations, Part 1
The idea is simple: use two pointers, left and right, first left pointer points to the left most bit, right pointer points to right most bit, check whether these 2 bit values are same, loop all 32 bit.
public static boolean isPalindrome(int n) {
int count = 32;
int right = 1;
int left = 1 << (32 - 1);
while (count > 0) {
int leftBitValue = n & left, rightBitValue = n
& right;
if (!((leftBitValue == 0 && rightBitValue == 0) || (leftBitValue != 0 && rightBitValue != 0))) {
return false;
}
left = left >> 1;
right = right << 1;
count -= 2;
}
return true;
}
Variant: Determine whether bit-wise representation of the integer is a palindrome. Ignore all leftmost zeros.This means 5 = 101b is also a palindrome.
The idea comes from this link, I just converted it to java code:
public static boolean isPalindrome(int x) {
int original = x, reverse = 0;
while (x != 0) {
reverse <<= 1;
reverse += x & 1;
x >>>= 1;
}
return reverse == original;
}
ReferencesFun with Bitwise Operations, Part 1