Amazon Interview Question
Software Engineer / DevelopersPlease make sure to typecast the variables to unsigned integer and then do the right shift operations.....
If integer is right shifted, then it is arithmetic right shift.
If unsigned integer is right shifted then it is logical right shift.
This mistake I am seeing in almost all the posts of this forum....
Do we need to consider all bits in sizeof(int)??
Or only the number of digits required to represent that integer in binary notaion.
e.g. lets say sizeof int is 4 byte=32 bits
so 5 = 00000000000000000000000000000101
or we need to consider only 101
int palindrome(int x){
int i ;
for(i = 0; i < 32; i++){
if( ( (x >> 31 - i) ^ ( x & (1 << i)) ) != 0)
return 0;
}
return 1;
}
#define TRUE 1
#define FALSE 0
int is_palindrome(int x)
{
int reverse = 0;
int result;
int y = abs(x);
while (y != 0) {
reverse = reverse << 1;
if ((y & 1))
reverse = reverse | 1;
y = y >> 1;
}
result = reverse & abs(x);
if (x < 0) result = 0 - result;
return (x == result) ? TRUE : FALSE;
}
#define isOne(num,pos) (( num & ( 1 << pos ) ) ? TRUE : FALSE )
int isPalindrome( int num ) {
for( pos = 15 ; pos != -1 ; pos-- )
res = res + ( ( isOne(num,pos) ) ? ( 1 << (15 - pos) ) : 0 );
return ( num == res );
}
#define isOne(num,pos) (( num & ( 1 << pos ) ) ? TRUE : FALSE )
int isPoli( int num ) {
int pos;
for( pos = 15 ; pos != 7 ; pos-- )
if( isOne( num, pos ) != isOne( num, 15 - pos ) ) return FALSE;
return TRUE;
}
This is another version......
#include<stdio.h>
void main()
{
unsigned int num = 12345;
unsigned char rmb, lmb, ctr;
for(ctr=1; ctr<(sizeof(num) * 8)/2; ctr++) {
rmb = (num & (1<<((sizeof(num) * 8) - ctr ))) == 0 ? 0 : 1;
lmb = (num & (1<< (ctr-1))) > 0 ? 1 :0;
if(rmb!=lmb) break;
}
if(rmb==lmb) printf("Pali");
else printf("! Pali");
}
@Anonymous: it doesn't matter. Here is my solution.
- Googler June 20, 2011