Amazon Interview Question
Software Engineer in Testsdidnt get the question
suppose how 0110 be a palindrome????
wy are u taking the leading zero if i take like this 0110= 0000110 then????
i think we should take till 1 means 6=110 is it or please elaborate what to do ??
Same problem here..how we are defining
4= 0100 but we can write 4 as 00100 and its also palindrome .
#include<iostream>
using namespace std;
#include<stdlib.h>
#include<string.h>
char *convert(int num)
{
char *str=new char(20);
char *st="0123456789";
int x,i=0;;
while(num)
{
x=num%2;
str[i++]=st[x];
num=num>>1;
}
str[i]='\0';
return str;
}
bool check(char *str)
{
int flag=1;
for(int i=0,j=strlen(str)-1;i<=j;i++,j--)
{
if(str[i]==str[j])
flag=1;
else
{
flag=0;
break;
}
}
if(flag)
return true;
else
return false;
}
int main()
{
int num;
cout<<"entr num\n";
cin>>num;
char *str=new char(20);
strcpy(str,convert(num));
if(check(str))
cout<<"is palin\n";
else
cout<<"not a palindrom\n";
return 0;
}
I'm considering all the bits of the given number. So let N is the original number. Now initially nLeft = N and nRight = N. nLeft & nRight represent result of the number N when its left & right shifted by 1 respectively. Algo is as follows:
while (nLeft != 0 && nRight != 0)
{
if (first bit of nRight != last bit of nLeft)
{
number is not palindrom
break;
}
nRight = nRight >> 1;
nLeft = nLeft << 1;
}
if (nLeft == nRight)
{
number is palindrom
}
Hope I'm clear enough. Plz comment on the approach.
Nice que.
- Rahul D July 22, 2011What about following logic:
reverse the bits of number for example number is 01100110
int dig = 1;
int rev = 0;
for(i=0;i<8;++i)
{
if(number & (dig<<i))
rev = pow(2,(7-i)) + rev;
}
if(! rev ^ number)
{
print palindrom
}
else
{
print bye-bye :)
}