Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
My code:
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m.bit_length() > n.bit_length():
return 0
size = (m ^ n).bit_length()
return n & (~((1 << size)-1))
#1<<size get the bit_length of and operation
#~ operation for Complement operation
def rangeBitwiseAnd2(self, m, n):
if not m or not n or m==n:
return m&n
lm,ln = int(math.log(m,2)),int(math.log(n,2))
if lm != ln:
return 0
return 2**lm + self.rangeBitwiseAnd(m%(2**lm),n%(2**ln))
Solution: https://leetcode.com/problems/bitwise-and-of-numbers-range/