FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/bit/flip_bit_longest_sequence.py at master · Mu-L/algorithms-python · GitHub
Mu-L
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
bit
/
flip_bit_longest_sequence.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
30 lines (23 loc) · 707 Bytes
Breadcrumbs
algorithms-python
/
algorithms
/
bit
/
flip_bit_longest_sequence.py
Copy path
File metadata and controls
30 lines (23 loc) · 707 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
You have an integer and you can flip exactly one bit from a 0 to 1.
Write code to find the length of the longest sequence of 1s you could create.
For example:
Input: 1775 ( or: 11011101111)
Output: 8
"""
def
flip_bit_longest_seq
(
num
):
curr_len
=
0
prev_len
=
0
max_len
=
0
while
num
:
if
num
&
1
==
1
:
# last digit is 1
curr_len
+=
1
elif
num
&
1
==
0
:
# last digit is 0
if
num
&
2
==
0
:
# second last digit is 0
prev_len
=
0
else
:
prev_len
=
curr_len
curr_len
=
0
max_len
=
max
(
max_len
,
prev_len
+
curr_len
)
num
=
num
>>
1
# right shift num
return
max_len
+
1
Back
|
FazBrowse Home
|
New Git URL