Skip to content
Problem 201 · LeetCode 201(opens in a new tab)

Bitwise AND of Numbers Range

MediumBit manipulation

You get two integers, left and right, with left ≤ right. Take every whole number from left to right, both ends included, and combine them all with bitwise AND.

Return the result. The range can hold about two billion numbers, so think about what the AND does to each bit rather than looping over all of them.

Example 1

Input:  left = 26, right = 31
Output: 24
Why:    26 to 31 all start with 11 in binary; every lower bit is 0 somewhere
2 more examples and the constraints

Example 2

Input:  left = 9, right = 9
Output: 9
Why:    one number, so the AND is the number itself

Example 3

Input:  left = 1, right = 2147483647
Output: 0
Why:    1 & 2 is already 0, and a zero bit stays zero

Constraints

  • 0 ≤ left ≤ right ≤ 2,147,483,647 (that is, 2³¹ − 1)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. AND every numberO(right − left)
  2. Shift to the shared prefixO(log right)
  3. Clear right's low bitsO(log right)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for left = 2³⁰, right = 2³¹ − 1Verdict
AND every numberO(right − left)
Over a billion steps; too slow
Shift to the shared prefixO(log right)
At most 31 shifts
Clear right's low bitsO(log right)
Best; one round per set bit

right − left = how many numbers are in the range; log right = number of bits, at most 31.

Edge cases to test

  • left equals right. The answer is that number. Both fast loops end before they start.
  • left is 0. Zero has no set bits, so the answer is 0.
  • The range crosses a power of two. 15 to 16 gives 0: 01111 and 10000 share no prefix.
  • right is 2³¹ − 1. In Java or C++, a for loop with an int counter overflows at x++; use a wider type in the brute force.

Common mistakes

  • Looping over the whole range with no early stop, which times out on wide ranges.
  • Using an int loop counter up to 2,147,483,647, which overflows and never ends.
  • Returning the shared prefix without shifting it back to its place.

How to talk through it

  1. 1Clarify. Is left always at most right? Can they be 0? The range can hold two billion numbers.
  2. 2Start simple. AND every number, stopping at 0. Correct, but O(right − left).
  3. 3Think per bit. A bit survives only if no number in the range has it at 0. Below the first differing bit, every bit rolls over.
  4. 4Code the prefix. Clear right's lowest set bit while right > left, or shift both until equal. O(log right).
  5. 5Test out loud. 26 to 31 gives 24, 9 to 9 gives 9, and 15 to 16 gives 0.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?