Created
August 8, 2022 07:45
-
-
Save buggysolid/feebd456b4ba98ae9f562f35f9370818 to your computer and use it in GitHub Desktop.
Find longest sequence of 1’s in binary representation with one flip
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
""" | |
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