File: binary-gap/solution.py

Date: 2026-06-06

Time: 15:22

binary-gap/solution.py

Purpose

This file solves LeetCode 868 — Binary Gap. It finds the longest distance between any two adjacent 1 bits in the binary representation of a positive integer. It's a standalone solution module following the repo's convention of one problem per directory.

Key Components

binary_gap(n: int) -> int — the sole exported function. Contract:

Three local variables drive the logic:

Patterns

Bit-scanning via right-shift loop. Rather than converting to a string with bin(), the code examines one bit at a time by masking with & 1 and shifting n >>= 1. This is the idiomatic low-level approach — O(log n) iterations, no string allocation.

Sentinel-based tracking. lastone = -1 distinguishes "no 1 seen yet" from "first 1 was at position 0." The if lastone >= 0 guard ensures we only compute a gap after seeing at least two 1 bits.

Dependencies

Imports: None — pure computation with no standard library or project imports.

Imported by: binary-gap/testsolution.py directly. The "Imported By" list in the prompt shows hundreds of test files, which is an artifact of the repo's shared test infrastructure — those files don't actually call binarygap, they import the test runner or shared fixtures.

Flow

1. Initialize maxgap = 0, lastone = -1, pos = 0.

2. Loop while n > 0 (bits remain):

3. Return max_gap.

For n = 22 (binary 10110): positions of 1 bits are 1, 2, 4. Gaps are 2-1=1 and 4-2=2. Returns 2.

Invariants

Error Handling

None. The function assumes valid input per the LeetCode constraint (1 <= n <= 10^9). Passing 0 would skip the loop entirely and return 0 — harmless but outside spec. Negative integers would loop indefinitely in CPython (arbitrary-precision integers never reach 0 via >>= 1 when negative), but the docstring constrains the domain.

Topics to Explore

Beliefs