Finding the largest gap between ones in a binary number makes for a great coding exercise.
Where is the state in this problem?
- We need to know if we’re in a line of zeros (or between ones) in the number.
- We need to count the zeros.
- We need to track the maximum count of zeros we’ve seen between ones in the whole number.
Examples: 9 - 1001 - Max number of zeros is 2. 1041 - 10000010001 - Max number of zeros is 5.
In order to solve this we need to iterate over bits in the number. When we encounter 1 we need to evaluate whether we’re inside a line of zeros. We conditionally set the new maximum or flag that we’re inside the line of zeros. In both cases we need to reset the counter. When we encounter 0 we just check whether we’re inside the line of zeros and increment the counter. At the end of the cycle we shift the bits to the right.
| |