Problem
Given two integersleft and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Examples
Constraints
- 0 <= left <= right <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 201 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 201 # by problem number
lcpy gen -s bitwise_and_of_numbers_range # by problem name
left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Input: left = 5, right = 7
Output: 4
Input: left = 0, right = 0
Output: 0
Input: left = 1, right = 2147483647
Output: 0
class Solution:
# Time: O(log n) where n is the value of right (number of bits)
# Space: O(1)
def range_bitwise_and(self, left: int, right: int) -> int:
# The AND of the range equals the common most-significant bit prefix
shift = 0
while left < right:
left >>= 1
right >>= 1
shift += 1
return left << shift
| Time | Space |
|---|---|
| O(log n) where n is the value of right (number of bits) | O(1) |