Classic problem #201MediumBit Manipulation
Bitwise AND of Numbers Range
Real-world version: Combining a Whole Range With ANDTracked 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)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's