How to find the length of the longest consecutive zeroes in the binary representation of a number in Python

2 Answers

0 votes
def longest_consecutive_zeroes(n):
    max_count = 0
    current_count = 0

    while n > 0:
        if (n & 1) == 0:  # Check if the least significant bit is 0
            current_count += 1
            max_count = max(max_count, current_count)  # Update max_count
        else:
            current_count = 0  # Reset count when a 1 is encountered

        n >>= 1  # Right shift the number

    return max_count


num = 11298  # Binary: 0010110000100010

print("Longest consecutive zeroes:", longest_consecutive_zeroes(num))


'''
run:

Longest consecutive zeroes: 4

'''

 



answered Sep 14 by avibootz
0 votes
def longest_consecutive_zeroes(n: int) -> int:
    # Return the longest run of consecutive zeroes in the binary representation of n.
    max_count = current_count = 0
    
    binary_string = bin(n)[2:] # Convert to binary string 
    
    for bit in binary_string:  # Iterate over each bit
        if bit == '0':
            current_count += 1
            max_count = max(max_count, current_count)
        else:
            current_count = 0
 
    return max_count
 
 
num = 11298  # Binary: 0010110000100010
 
print(f"Longest consecutive zeroes: {longest_consecutive_zeroes(num)}")
 
 
 
'''
run:
 
Longest consecutive zeroes: 4
 
'''

 



answered Sep 14 by avibootz
edited Sep 15 by avibootz
...