Bonus
I noticed that each answer uses bin()
to calculate the longest segment of ones. However, it's not really needed since this approach has an additional O(n)
space complexity (as you recall it from the previous paragraph, n
- number of binary digits).
We could just use bitwise operators to achieve the same result. For example, let's say there's a number 1100011101
. It has 3
separate segments of ones: Now, let's play a bit - we will calculate a left shifted version of x
and then perform bitwise AND
on it. Then, for the shifted version we will calculate its left shifted number and so on.
1 1 0 0 0 1 1 1 0 1 0 (x)
&
1 0 0 0 1 1 1 0 1 0 0 (x << 1)
---------------------
1 0 0 0 0 1 1 0 0 0 0 y = ((x) & (x << 1))
1 0 0 0 0 1 1 0 0 0 0 (y)
&
0 0 0 0 1 1 0 0 0 0 0 (y << 1)
---------------------
0 0 0 0 0 1 0 0 0 0 0 z = ((y) & (y << 1))
0 0 0 0 0 1 0 0 0 0 0 (z)
&
0 0 0 0 1 0 0 0 0 0 0 (z << 1)
---------------------
0 0 0 0 0 0 0 0 0 0 0 ((z) & (z << 1))
So, as you can see it took us 3
steps to reach 0
. But 3
is also the length of the longest segment of ones. And it's not a coincidence because bitwise AND
of a number and its shifted version shortens each segment of ones by 1
. Hence, the longest segment will lose all its ones after < length of the longest segment of ones > steps.
Now, the the code
...
maxLength = 0
while number > 0:
leftShiftedNumber = number << 1
number = number & leftShiftedNumber
maxLength += 1
print (str(maxLength))
...