Amazon Interview Question
Software Engineer / Developerslets take an example
0xabcddcba
Byte0 is Reverse of Byte3 (ba .. ab)
Byte1 is Reverse of Byte2 (dc ..cd)
Logic is simple, just compare B3 with reverse of B0 && B1 with reverse of B2. if both evaulates to TRUE, given bit pattern of an integer is a palindrome.
I assume there exists a lookup table which already stores the reverse of numbers from 0-256.
if((lookupTable[n&0xff]) == (n>>24 & 0xff)
&& (lookupTable[n>>8 & 0xff]) == (n>>16 & 0xff)
)
{
printf("Bit pattern of <%d> is a palindrome\n", n);
}
// copy the bit pattern backwards & xor with original.
// if result is 0 then its palindrome,return true
// else false
bool isPalindrome( int x )
{
size_t t = sizeof(int)*CHAR_BIT; // num of bits in the int
int x_rev = 0; // to store the reverse pattern
const int mask = 1;
for ( int i = 0; i < t; ++i ) {
// the bit at position t-i must
// be the bit at position i for a
// palindrome! 0 bits are already there
// in x_rev. Only 1s need to be
// determined
if ( x & (mask << i) ) {
x_rev |= mask << t - i;
}
}
return !(x^x_rev);
}
- Anonymous February 26, 2010