Tuesday, October 30, 2012

Bit stream has an alternating pattern or not

Write a function that returns true if the bit stream has an alternating pattern.
For example 000000101010 would return true and 0000001010000 would return false. Also write test cases for the function.

Strategy:

bool patternCheck(int a)
{
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;
}

1 comment:

  1. Cant we do this way? :
    int b = a>>1;
    if( (a & b) == 0) {return true;}
    else { return false;}

    ReplyDelete