Given a binary representation of an integer say 15 as 1111, find the maximum longest continous sequence of 0s. The twist is it needs to be done in log N. I could think of O(N) solution. but couldn't go for log(N).
For example. 10000101
the answer should be 4, because there are 4 continouos zeroes.
----------------------------------------------------------------------------------------
It is possible. The question is reduced to how you can represent a number as addition of numbers which are power of 2
N = 133
= 128 + 5
= 128 + 4 +1
Now, for each such number above, you know how many bits you need to represent that number and max diff of bits between two consecutive numbers is your answer.
So for N = 128 + 4 +1 , you need bits 8(for 128), 3(for 4) and 1(for 1), so the answer is
Max[ (7-3) and (2-1) ] = 4. Why 7 and 2? Because with 8 bits to represent 128, MSB is set already so max you can have 7 bits 0 and same with 4 where you have MSB set so max 2 remaining bits.
int Max =0;
while(N)
{
int NumBits = CEILING(log N);
int NextN = N - pow(2, NumBits)
if(NextN == 0)
{
// this means, the number is power of 2, just find trailing 0s and return max
if(NumBits > max)
max = NumBits;
return max;
}
int NextNumBits = CEILING(log NextN);
if(NumBits - NextNumBits > max)
max = NumBits - NextNumBits;
N = NextN;
}
return max;
As an example N = 133 ==> 10000101
NumBits = 7 (= CEILING(log 133))
NextN = 133 - 128 ( = pow(2,7) ) now NextN becomes 5
NumZero = NumBits - CEILING(long NextN)) = 7 - 3 = 4
Check if NumZero is max so far,
Make N = NextN and repeat loop then return max
-----------------------------------------Reconsider in 20190725--------------------------------
If N is the length of binary representation, O(N) is easy when converting into binary representation, i.e., log(n) when n is the number. I don't think the above solution makes sence.