Last active
September 6, 2019 13:10
-
-
Save jadechip/41c130a678f6d0b5b5775fc994e18c4e to your computer and use it in GitHub Desktop.
Programming challenge: Binary Gap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solution(N): | |
max_value = 2147483647 | |
min_value = 1 | |
if (N < min_value or N > max_value): | |
return 0 | |
binary = bin(N) | |
return find_gaps(list(binary)) | |
def find_gaps(binary_list, gaps=[]): | |
first_index = 0 | |
second_index = 0 | |
# Base case | |
if "1" in binary_list: | |
first_index = binary_list.index("1") | |
remaining_slice = binary_list[first_index + 1:] | |
if "1" in remaining_slice: | |
second_index = remaining_slice.index("1") | |
if second_index > 0: | |
gaps.append(second_index) | |
# Recursive case | |
# Repeat process with the remaining slice as input | |
return find_gaps(remaining_slice[second_index:], gaps) | |
return 0 if not gaps else max(gaps) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment