Scan bit positions from least significant to most significant, retaining the previous set-bit position and maximizing the gap.
Complexity
O(log n) time and O(1) space.
Find the greatest distance between consecutive set bits in an integer.
Scan bit positions from least significant to most significant, retaining the previous set-bit position and maximizing the gap.
O(log n) time and O(1) space.
package main
func binaryGap(n int) int {
previous, best := -1, 0
for position := 0; n > 0; position, n = position+1, n>>1 {
if n&1 == 1 {
if previous >= 0 && position-previous > best {
best = position - previous
}
previous = position
}
}
return best
}
class Solution:
def binaryGap(self, n: int) -> int:
previous, best, position = -1, 0, 0
while n:
if n & 1:
if previous >= 0: best = max(best, position - previous)
previous = position
position, n = position + 1, n >> 1
return best
function binaryGap(n: number): number {
let previous = -1;
let best = 0;
for (let position = 0; n > 0; position += 1, n >>= 1) if ((n & 1) === 1) { if (previous >= 0) best = Math.max(best, position - previous); previous = position; }
return best;
}