Program to find longest consecutive run of 1s in binary form of n in Python

Suppose we have a non-negative value n, we have to find the length of the longest consecutive run of 1s in its binary representation.

So, if the input is like n = 1469, then the output will be 4, because binary representation of 1469 is "10110111101", so there are four consecutive 1s.

Approach

To solve this, we will follow these steps ?

  • count := 0
  • while n is not same as 0, do
    • n := n AND (n after shifting one bit to the left)
    • count := count + 1
  • return count

How It Works

The algorithm uses bit manipulation where n & (n removes the rightmost set of consecutive 1s in each iteration. The number of iterations equals the length of the longest consecutive run.

Binary: 10110111101 (1469) Step 1: 10110111101 & 01101111010 = 00100111000 Step 2: 00100111000 & 01001110000 = 00000110000 Step 3: 00000110000 & 00001100000 = 00000100000 Step 4: 00000100000 & 00001000000 = 00000000000 Result: 4 iterations = longest run of 4 consecutive 1s

Example

Let us see the following implementation to get better understanding ?

def solve(n):
    count = 0
    while n != 0:
        n = n & (n << 1)
        count = count + 1
    
    return count

n = 1469
print(f"Binary of {n}: {bin(n)}")
print(f"Longest consecutive 1s: {solve(n)}")

The output of the above code is ?

Binary of 1469: 0b10110111101
Longest consecutive 1s: 4

Alternative Approach Using String Method

We can also solve this by converting to binary string and finding the longest sequence of '1's ?

def solve_string(n):
    binary = bin(n)[2:]  # Remove '0b' prefix
    max_count = 0
    current_count = 0
    
    for bit in binary:
        if bit == '1':
            current_count += 1
            max_count = max(max_count, current_count)
        else:
            current_count = 0
    
    return max_count

# Test with multiple values
test_values = [1469, 156, 7, 0, 15]
for n in test_values:
    print(f"n = {n}, binary = {bin(n)}, longest run = {solve_string(n)}")
n = 1469, binary = 0b10110111101, longest run = 4
n = 156, binary = 0b10011100, longest run = 3
n = 7, binary = 0b111, longest run = 3
n = 0, binary = 0b0, longest run = 0
n = 15, binary = 0b1111, longest run = 4

Comparison

Method Time Complexity Space Complexity Best For
Bit Manipulation O(longest run) O(1) Memory efficiency
String Method O(log n) O(log n) Readability

Conclusion

The bit manipulation approach efficiently finds the longest consecutive run of 1s using the property that n & (n removes the rightmost consecutive 1s. The string method is more intuitive but uses additional memory for the binary string conversion.

Updated on: 2026-03-26T17:37:56+05:30

794 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements