Bitwise AND of Numbers Range

Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

 

Example 1:

Input: left = 5, right = 7
Output: 4

Example 2:

Input: left = 0, right = 0
Output: 0

Example 3:

Input: left = 1, right = 2147483647
Output: 0

 

Constraints:

  • 0 <= left <= right <= 231 - 1
SOLUTION:
class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> int:
        if left == 0 or right == 0:
            return 0
        a = "{:b}".format(left)
        b = "{:b}".format(right)
        if len(a) != len(b):
            return 0
        res = 1 << len(a) - 1
        return res + self.rangeBitwiseAnd(left - res, right - res)

Comments

Popular posts from this blog

Encrypt and Decrypt Strings

Degree of an Array

Minimum Sum of Four Digit Number After Splitting Digits