ZhangZhihui's Blog  

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

 

My Solution:

class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> int:
        if left == right:
            return left
        
        if left == 0:
            return 0
        
        bin_left = bin(left)[2:]
        bin_right = bin(right)[2:]
        len_left = len(bin_left)
        len_right = len(bin_right)
        
        if len_left < len_right:
            return 0
        
        i = 0
        while i < len_left:
            if bin_left[i] == bin_right[i]:
                i += 1
            else:
                break
        diff_bits = len_left - i
        return int(bin_left[:i] + ''.join(['0'] * diff_bits), 2)

 

 

ChatGPT's Solution:

class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> int:
        shift = 0
        # Find the common prefix
        while left < right:
            left >>= 1
            right >>= 1
            shift += 1
        return left << shift

 

 

posted on 2025-04-04 12:43  ZhangZhihuiAAA  阅读(6)  评论(0)    收藏  举报