Skip to content

Instantly share code, notes, and snippets.

@buggysolid
Created August 8, 2022 07:45
Show Gist options
  • Save buggysolid/feebd456b4ba98ae9f562f35f9370818 to your computer and use it in GitHub Desktop.
Save buggysolid/feebd456b4ba98ae9f562f35f9370818 to your computer and use it in GitHub Desktop.
Find longest sequence of 1’s in binary representation with one flip
"""
https://www.geeksforgeeks.org/find-longest-sequence-1s-binary-representation-one-flip/
Input : 1775
Output : 8
Binary representation of 1775 is 11011101111.
After flipping the highlighted bit, we get
consecutive 8 bits. 11011111111.
Input : 12
Output : 3
Input : 15
Output : 5
Input : 71
Output: 4
Binary representation of 71 is 1000111.
After flipping the highlighted bit, we get
consecutive 4 bits. 1001111.
"""
def longest_sequence(input_):
input_ = bin(input_).strip('0b')
boundaries = input_.split('0')
if len(boundaries) > 1:
longest_subsequence = len(boundaries[-1]) + len(boundaries[-2]) + 1
else:
longest_subsequence = len(boundaries[-1]) + 1
return longest_subsequence
def main():
for entry in [1775, 12, 15, 71]:
print(f"Longest subsequence of 1's in {entry} is {longest_sequence(entry)}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment