Compute the bitwise AND of every integer in the range [left, right]

Quick Overview

Return the bitwise AND of every integer in an inclusive range [left, right] where the values go up to 2^31 - 1. It tests reasoning about the binary form of consecutive numbers and finding a method that runs in a few dozen steps, since looping over the range is far too slow.

Compute the bitwise AND of every integer in the range [left, right]

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given two integers `left` and `right` that represent the range `[left, right]`, return the bitwise AND of all numbers in this range, inclusive. ### Function Signature ```python def range_bitwise_and(left: int, right: int) -> int: ``` ### Constraints - `0 <= left <= right <= 2^31 - 1` ### Examples ```text Input: left = 5, right = 7 Output: 4 ``` 5 in binary is `101`, 6 is `110` and 7 is `111`. The AND `101 & 110 & 111` is `100`, which is 4. ```text Input: left = 0, right = 0 Output: 0 ``` The range contains only 0, so the result is 0. ```text Input: left = 26, right = 30 Output: 24 ``` The range holds `11010`, `11011`, `11100`, `11101` and `11110`. Only the top two bits are 1 in all five numbers, so the result is `11000`, which is 24.

Overview: Return the bitwise AND of every integer in an inclusive range [left, right] where the values go up to 2^31 - 1. It tests reasoning about the binary form of consecutive numbers and finding a method that runs in a few dozen steps, since looping over the range is far too slow.

Nov 24, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

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

Function Signature

def range_bitwise_and(left: int, right: int) -> int:

Constraints

  • 0 <= left <= right <= 2^31 - 1

Examples

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

5 in binary is 101, 6 is 110 and 7 is 111. The AND 101 & 110 & 111 is 100, which is 4.

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

The range contains only 0, so the result is 0.

Input: left = 26, right = 30
Output: 24

The range holds 11010, 11011, 11100, 11101 and 11110. Only the top two bits are 1 in all five numbers, so the result is 11000, which is 24.