Problem
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Algorithm
Determine whether each 1 will become 0. Use the power of 2 to turn the 1 of left to 0, if the sum is no more than right, the number is in the range and do AND.
Code
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
ans = left & right
base = 1
bits = 0
while base <= right:
if base & left and base + left <= right:
ans &= base + left
base *= 2
return ans