201. Bitwise AND of Numbers Range
201. Bitwise AND of Numbers Range
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
res = left
left += 1
while left <= right:
res = res & left
left += 1
return res
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
shift = 0
# find the common 1-bits
while m < n:
m = m >> 1
n = n >> 1
shift += 1
return m << shift
Brian Kernighan's Algorithm
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
while m < n:
# turn off rightmost 1-bit
n = n & (n - 1)
return m & n