Isaac Emmanuel
09 Sept 2026•EasyGo / Python / TypeScript

Binary Gap

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.

Complexity

O(log n) time and O(1) space.

Solution files

Go•binary-gap/solution.go
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
}
Python•binary-gap/solution.py
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
TypeScript•binary-gap/solution.ts
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;
}