> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Bitwise AND of Numbers Range Python Solution

> Tested Python solution for LeetCode 201 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 201, Medium. Topics: Bit Manipulation. [View on LeetCode](https://leetcode.com/problems/bitwise-and-of-numbers-range/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 201   # by problem number
lcpy gen -s bitwise_and_of_numbers_range   # by problem name
```

## Problem

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

### Examples

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

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

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

### Constraints

* 0 \<= left \<= right \<= 2^31 - 1

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/bitwise_and_of_numbers_range/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/bitwise_and_of_numbers_range/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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
```

## Complexity

| Time                                                    | Space |
| ------------------------------------------------------- | ----- |
| O(log n) where n is the value of right (number of bits) | O(1)  |

## Tags

[NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
