All problems
1158MediumBit Manipulation

Combining a Whole Range With AND

Tracked in this browser only
Write code

Trains the technique from

LeetCode 201Bitwise AND of Numbers Range

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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