Wednesday, August 18, 2010

Mirosoft Question: Suppose you are getting an infinite binary stream of characters then after any point of time you need to print whether the number is divisible by 3 or not.

Solution:
int rem = 0;
while(incomingNextBit)
{
   bool nextBit = getNextBit();
   if(nextBit == 0)
        rem = rem * 2;
   else
        rem = rem *2 + 1;
   rem = rem % 3;
}
At any time when you want to check wether number is divisble by 3 check rem %3.
This solution does not store the value of actual number.


5 comments:

  1. Please give you logic for better understanding

    ReplyDelete
  2. initially stage is set to 0;
    n = nextbit();
    switch(n)
    {
    case 0:
    if(stage ==1)
    stage =2;
    else if( stage ==2)
    stage = 1;
    break;
    case 1:
    if(stage ==0)
    stage = 1;
    else if (stage ==1)
    stage = 0;
    else if( stage ==2)
    stage =2;
    break;
    }

    at any point of time if stage = 0 then no is div by 3;

    ReplyDelete
  3. Jitendra .. conversion of a c++ code to c, I don't think its a big task, you can do it on your own

    ReplyDelete