Advertisement
dennoh

Max Binary Gap

Jan 8th, 2021
1,038
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.60 KB | None | 0 0
  1. def max_gap(x):
  2.     max_gap_length = 0
  3.     current_gap_length = 0
  4.     for i in range(x.bit_length()):
  5.         if x & (1 << i):
  6.             # Set, any gap is over.
  7.             if current_gap_length > max_gap_length:
  8.                 max_gap_length = current_gap_length
  9.             current_gap_length = 0
  10.         else:
  11.             # Not set, the gap widens.
  12.             current_gap_length += 1
  13.     # Gap might end at the end.
  14.     if current_gap_length > max_gap_length:
  15.         max_gap_length = current_gap_length
  16.     return max_gap_length
  17.  
  18. if __name__ == "__main__":
  19.     print(max_gap(50))
  20.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement