Show problems as
Classic problem #201MediumBit Manipulation

Bitwise AND of Numbers Range

Real-world version: Combining a Whole Range With AND
Tracked in this browser only
Read Bitwise AND of Numbers Range on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Take every whole number from left to right, both ends included, and combine the lot with a bitwise AND.

Return the result.

Examples

Example 1

Input
left = 12, right = 15
Output
12

All four numbers agree on their top bits and differ beneath, so only the agreed part survives.

Example 2

Input
left = 8, right = 16
Output
0

The range crosses a power of two, so no bit place stays set right the way through.

Example 3

Input
left = 7, right = 7
Output
7

The range holds a single number, so that number is the result.

Constraints

  • 0 <= left <= right <= 2147483647
  • left <= right

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def range_bitwise_and(left: int, right: int) -> int:
Java
public int rangeBitwiseAnd(int left, int right)