Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python

When working with binary representations, we sometimes need to check if consecutive blocks of 0s and 1s have the same length. This means that all groups of consecutive identical bits should have equal sizes.

For example, if we have the number 455, its binary representation is 111000111. Here we have three consecutive 1s, followed by three consecutive 0s, followed by three consecutive 1s − all blocks have the same length of 3.

Problem Statement

Given a number, we need to check whether its binary representation has the same number of consecutive blocks of 0s and 1s. Note that 0 and numbers with all 1s are not considered valid for this check.

Algorithm Steps

To solve this problem, we follow these steps ?

  • Convert the number to its binary representation
  • Count the length of each consecutive block of identical bits
  • Store all block lengths in a set
  • If the set contains only one unique length, all blocks are equal

Implementation

def check_equal_blocks(num):
    # Convert to binary and remove '0b' prefix
    bin_form = bin(num).replace("0b", "")
    block_lengths = set()
    count = 1
    
    # Count consecutive identical bits
    for i in range(len(bin_form) - 1):
        if bin_form[i] == bin_form[i + 1]:
            count += 1
        else:
            block_lengths.add(count)
            count = 1
    
    # Add the last block length
    block_lengths.add(count)
    
    # Check if all blocks have the same length
    return len(block_lengths) == 1

# Test with example
num = 455
result = check_equal_blocks(num)
print(f"Number: {num}")
print(f"Binary: {bin(num)[2:]}")
print(f"Equal blocks: {result}")
Number: 455
Binary: 111000111
Equal blocks: True

Testing with Different Examples

def check_equal_blocks(num):
    bin_form = bin(num).replace("0b", "")
    block_lengths = set()
    count = 1
    
    for i in range(len(bin_form) - 1):
        if bin_form[i] == bin_form[i + 1]:
            count += 1
        else:
            block_lengths.add(count)
            count = 1
    
    block_lengths.add(count)
    return len(block_lengths) == 1

# Test various numbers
test_numbers = [455, 51, 85, 7, 255]

for num in test_numbers:
    binary = bin(num)[2:]
    result = check_equal_blocks(num)
    print(f"Number: {num:3d} | Binary: {binary:>8s} | Equal blocks: {result}")
Number: 455 | Binary: 111000111 | Equal blocks: True
Number:  51 | Binary:   110011 | Equal blocks: True
Number:  85 | Binary:  1010101 | Equal blocks: True
Number:   7 | Binary:      111 | Equal blocks: True
Number: 255 | Binary: 11111111 | Equal blocks: True

How It Works

The algorithm works by iterating through the binary string and comparing each bit with the next one. When consecutive bits are the same, we increment a counter. When they differ, we store the counter value in a set and reset the counter.

Using a set is key here because sets only store unique values. If all consecutive blocks have the same length, the set will contain only one element. If blocks have different lengths, the set will contain multiple elements.

Conclusion

This approach efficiently checks if all consecutive bit blocks in a binary representation have equal lengths. The solution uses a set to track unique block sizes, making it easy to determine if all blocks are uniform in length.

Updated on: 2026-03-25T14:30:42+05:30

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements