Binary Gap in Python

A binary gap is the longest sequence of consecutive zeros that are surrounded by ones on both sides in the binary representation of a positive integer. We need to find the maximum distance between two consecutive 1's in the binary representation.

For example, if the input is 22, the binary representation is 10110. There are gaps of length 1 (between positions 1 and 3) and length 2 would be the answer if we count the distance differently. Let's implement this step by step.

Algorithm

To solve this problem, we follow these steps:

  • Convert the number to binary representation
  • Find positions of all 1's in the binary string
  • Calculate distances between consecutive 1's
  • Return the maximum distance

Example Implementation

def binary_gap(n):
    # Convert to binary and remove '0b' prefix
    binary = bin(n)[2:]
    
    # Find positions of all 1's
    ones_positions = []
    for i, bit in enumerate(binary):
        if bit == '1':
            ones_positions.append(i)
    
    # If less than 2 ones, no gap exists
    if len(ones_positions) < 2:
        return 0
    
    # Find maximum gap between consecutive 1's
    max_gap = 0
    for i in range(1, len(ones_positions)):
        gap = ones_positions[i] - ones_positions[i-1] - 1
        max_gap = max(max_gap, gap)
    
    return max_gap

# Test with example
print(binary_gap(22))  # Binary: 10110
print(binary_gap(5))   # Binary: 101
print(binary_gap(8))   # Binary: 1000
1
1
0

Alternative Approach Using Class

class Solution:
    def binary_gap(self, n):
        binary_str = bin(n)[2:]  # Remove '0b' prefix
        
        max_gap = 0
        last_one_pos = -1
        
        for i, bit in enumerate(binary_str):
            if bit == '1':
                if last_one_pos != -1:
                    # Calculate gap between current and previous 1
                    gap = i - last_one_pos - 1
                    max_gap = max(max_gap, gap)
                last_one_pos = i
        
        return max_gap

# Test the solution
solution = Solution()
print(solution.binary_gap(22))  # Binary: 10110
print(solution.binary_gap(5))   # Binary: 101  
print(solution.binary_gap(6))   # Binary: 110
1
1
0

How It Works

Let's trace through the example with n = 22:

  • Binary representation of 22 is 10110
  • Positions of 1's are: 0, 2, 3
  • Gaps between consecutive 1's:
    • Between position 0 and 2: gap = 2 - 0 - 1 = 1
    • Between position 2 and 3: gap = 3 - 2 - 1 = 0
  • Maximum gap is 1

Edge Cases

def test_edge_cases():
    solution = Solution()
    
    # Single 1 - no gap possible
    print(f"binary_gap(1): {solution.binary_gap(1)}")    # Binary: 1
    
    # Power of 2 - no gap
    print(f"binary_gap(8): {solution.binary_gap(8)}")    # Binary: 1000
    
    # Consecutive 1's only
    print(f"binary_gap(7): {solution.binary_gap(7)}")    # Binary: 111
    
    # Large gap
    print(f"binary_gap(529): {solution.binary_gap(529)}")  # Binary: 1000010001

test_edge_cases()
binary_gap(1): 0
binary_gap(8): 0
binary_gap(7): 0
binary_gap(529): 4

Conclusion

The binary gap problem requires converting a number to binary, finding positions of 1's, and calculating the maximum distance between consecutive 1's. The solution runs in O(log n) time complexity where n is the input number.

Updated on: 2026-03-25T08:53:08+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements