📅  最后修改于: 2023-12-03 14:58:28.421000             🧑  作者: Mango
You are given a partially written function to solve the following problem:
def maxZeros(n):
'''Find the maximum number of consecutive zeros in the binary representation of given integer n.'''
# Initialize count variable
count = 0
# Loop to check consecutive zeros
while n!=0:
# Case - 1
if n%2==0:
# TODO: Code to be written here
pass
# Case - 2
elif n%2==1:
# TODO: Code to be written here
pass
return count
Your task is to complete the above function so that it passes all the test cases.
The function should return the expected output for the following test cases:
assert(maxZeros(45) == 4)
assert(maxZeros(550) == 4)
assert(maxZeros(1022) == 0)
To solve this problem, we need to understand that the maximum number of consecutive zeros in the binary representation of a number can be found by counting the number of trailing zeros in its binary representation.
For example, the binary representation of 45 is:
101101
The maximum number of consecutive zeros in this binary representation is 4, which occurs after the two ones in the middle. Therefore, we need to count the number of trailing zeros i.e. the number of zeros after the last one.
101101
^
To count the number of trailing zeros, we can repeatedly divide the given number by 2 as long as it is divisible by 2. Every time we divide it by 2, we shift its binary representation to the right by 1 bit. Eventually, this will leave us with the rightmost 1 in its binary representation. Then, the number of trailing zeros will be equal to the number of bits we shifted to the right.
101101 (45)
010110 (22)
001011 (11)
000101 (5)
000010 (2)
000001 (1)
In the above example, we divided 45 by 2 five times. Therefore, the maximum number of consecutive zeros in its binary representation is 5-1=4.
Now, let's complete the given function based on this logic:
def maxZeros(n):
'''Find the maximum number of consecutive zeros in the binary representation of given integer n.'''
# Initialize count variable
count = 0
# Loop to check consecutive zeros
while n!=0:
# Case - 1
if n%2==0:
count += 1 # Increment count of trailing zeros
n //= 2 # Right shift binary representation
# Case - 2
elif n%2==1:
n //= 2 # Right shift binary representation
return count
In this function, we check whether the current bit is 0 or 1. If it is 0, we increment the count of trailing zeros and right shift the binary representation of the number. If it is 1, we just right shift the binary representation. We repeat this until the binary representation becomes zero.
In this problem, we learned how to find the maximum number of consecutive zeros in the binary representation of a number. This involved counting the number of trailing zeros in its binary representation. We achieved this by repeatedly dividing the number by 2 and counting the number of bits shifted to the right.