CareerCup the maximum longest continous sequence of 0s

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. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值