Interview Question
Country: United States
I wasn't sure of the question until I start reading answers. But what if numbers such as BB are consider "alternating"?
//num represents the equivalent decimal
//logic is simple implementation using finite automata
// i am assuming tat strings like 0001010,00000101 are considered as
//alternate.
//the code is simple but i'd like to get a more compact code
int alternate(int num)
{
int a=0;
if(num&1)
{
a=4;
num>>=1;
while(num)
{
if((a==4)&&(num&1))
return 0;
else if((a==4)&&(!(num&1)))
a=5;
else if((a==5)&&(num&1))
{
a=4;
if(num==1)
a=5;
}
num>>=1;
}
}
else
{
a=1;
num>>=1;
while(num)
{
if((a==1)&&(!(num&1)))
return 0;
else if((a==1)&&(num&1))
a=2;
else if((a==2)&&(!(num&1)))
a=1;
num>>=1;
}
}
if((a==5)||(a==2))
return 1;
return 0;
}
bool alternate(int x)
{
int y = (x*3);
y>>=1;
y+=1;
if((y & (y-1))==0)
return true;
else return false;
}
am i missing something.. this sounded really simple.
bool patternCheck(int a)
- Ali_BABA January 24, 2012{
int b=a>>1;
/*if a=000000101010 then b=0=00000010101,,,,rightshift of a by 1*/
//now xor of a and b
int n=(a^b)+1;//n is in 2^n format if alternate bits are there
if(n & (n-1)) == 0) return true;
return false;
}