Advertisement
kosievdmerwe

Untitled

Oct 9th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. class Solution:
  2.     def rangeBitwiseAnd(self, left: int, right: int) -> int:
  3.         # Python has a dumb "bug" where right.bit_length() == 0 when right == 0
  4.         if right == 0:
  5.             return 0
  6.        
  7.         ans = right
  8.         for i in range(right.bit_length()):
  9.             cur = self.biggest_less_than_with_bit_zeroed(right, i)
  10.             # print(bin(cur)[2:].rjust(right.bit_length(), '0'), right.bit_length())
  11.             if cur >= left:
  12.                 ans &= cur
  13.         return ans
  14.            
  15.     def biggest_less_than_with_bit_zeroed(self, num: int, i: int) -> int:
  16.         """Returns the biggest integer less than num where bit i is zero"""
  17.        
  18.         # If the bit is already 0, then num is the largest.
  19.         if ((1 << i) & num) == 0:
  20.             return num
  21.        
  22.         num_bits = num.bit_length()
  23.        
  24.         mask = (1 << num_bits) - 1
  25.         right_mask = (1 << (i + 1)) - 1
  26.    
  27.         ans = num - (num & right_mask)
  28.         ans += right_mask >> 1
  29.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement