gary@interview:~/interview/coding/201-bitwise-and-….md$
$ cat ./coding/201-bitwise-and-of-numbers-range.md
[Coding]

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
--tags#Bit Manipulation
$ ls ./coding/ | grep -v 201-bitwise-and-of-numbers-range
265. Paint House II256. Paint House143. Reorder List1762. Buildings With an Ocean View
← cd ../codingcd ~