Bitwise AND of Numbers Range

Medium#201bit by bit

You get two numbers left ≤ right. Return the bitwise AND of every integer from left to right, both ends included. The range can hold billions of numbers, so going through them is too slow. Our example: left = 26, right = 30 — the answer is 24.

input
left, right: the ends of a range of integers, both included.
returns
The bitwise AND of every number from left to right: left & (left + 1) & … & right.
constraints
  • 0 ≤ left ≤ right ≤ 2³¹ − 1
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} left
 * @param {number} right
 * @return {number}
 */
function rangeBitwiseAnd(left, right) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more bit manipulation problems

Pattern “Bit manipulation” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.