Given a positive integer n, find and return the longest distance between any two adjacent 1’s in the binary representation of n. If there are no two adjacent 1’s, return 0.
n?
n into its binary representation using Python’s bin() function.def binaryGap(n: int) -> int:
# Convert the integer to binary string and strip the '0b' prefix
binary_representation = bin(n)[2:]
# Variable to store the maximum gap
max_gap = 0
# Previous index of '1' found
prev_index = -1
# Iterate through the binary representation
for i, char in enumerate(binary_representation):
if char == '1':
if prev_index != -1:
# Calculate the distance between current and previous '1'
max_gap = max(max_gap, i - prev_index)
# Update the previous index to current index
prev_index = i
return max_gap
This solution effectively handles the transformation of a number to its binary representation and identifies the maximum gap between consecutive ‘1’s in that representation. Let’s test it with a couple of inputs:
n = 22 (which is 10110 in binary)
n = 5 (which is 101 in binary)
n = 6 (which is 110 in binary)
n = 8 (which is 1000 in binary)
With this code and explanation, you should be able to handle the problem effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?