Skip to content
LC-0201 Medium LeetCode

201. Bitwise AND of Numbers Range

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 48% Topics: Bit Manipulation
View full problem on LeetCode

Reading material

Reference solution (spoiler · python)
# Time:  O(1)
# Space: O(1)

class Solution(object):
    # @param m, an integer
    # @param n, an integer
    # @return an integer
    def rangeBitwiseAnd(self, m, n):
        while m < n:
            n &= n - 1
        return n


class Solution2(object):
    # @param m, an integer
    # @param n, an integer
    # @return an integer
    def rangeBitwiseAnd(self, m, n):
        i, diff = 0, n-m
        while diff:
            diff >>= 1
            i += 1
        return n & m >> i << i

Solution from kamyu104/LeetCode-Solutions · MIT