-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary gap.py
More file actions
executable file
·45 lines (41 loc) · 1.5 KB
/
Copy pathbinary gap.py
File metadata and controls
executable file
·45 lines (41 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def decimalToBinary(n):
return bin(n).replace("0b", "")
def binary_gap(num):
x = str(decimalToBinary(num))
print(x)
ind = [i for i, val in enumerate(x) if val == '0']
print(ind)
if not ind:
return 0
else:
lengths = []
counter = 1
B = []
for j, val in enumerate(ind):
if j != len(ind) - 1:
if ind[j + 1] == ind[j] + 1:
counter += 1
B.append(ind[j])
print('list', j, ind[j], B)
else:
B.append(ind[j])
print('list', j, ind[j], B)
if B[-1] != len(x) - 1:
print('check first', j, B[0], B[-1], x[B[0] - 1], x[B[-1] + 1])
if B[0] != 0 and x[B[0] - 1] == '1' and x[B[-1] + 1] == '1':
print('APPENDING COUNTER', counter)
lengths.append(counter)
counter = 1
B = []
else:
B.append(ind[j])
print('list', j, ind[j], B)
if B[-1] != len(x) - 1:
print('check', B[0], B[-1], x[B[0] - 1], x[B[-1] + 1])
if B[0] != 0 and x[B[0] - 1] == '1' and x[B[-1] + 1] == '1':
lengths.append(counter)
if lengths:
return max(lengths)
else:
return 0
print('ANSWER', binary_gap(1041))