Bitwise AND Across a Range

You are given two integers left and right.

Consider all integers in the inclusive range [left, right]. Your task is to compute the bitwise AND of every number in this range and return the final result.

In other words, find: left & (left + 1) & (left + 2) & ... & right

where & represents the bitwise AND operator.

Example 1:

Input: left = 12, right = 15

Output: 12

Explanation:

The numbers in the range are 12, 13, 14, 15.

Their binary representations are:

  • 12 = 1100
  • 13 = 1101
  • 14 = 1110
  • 15 = 1111

Performing bitwise AND on all of them:

  • 1100 & 1101 & 1110 & 1111 = 1100

So, the answer is 12.

Example 2:

Input: left = 9, right = 11

Output: 8

Explanation:

The numbers in the range are 9, 10, 11.

Their binary representations are:

  • 9 = 1001
  • 10 = 1010
  • 11 = 1011

Performing bitwise AND on all of them:

  • 1001 & 1010 & 1011 = 1000

So, the answer is 8.

Now Your Turn!

Pick the correct output for the given input

Input: left = 6, right = 7

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= left <= right <= 231 - 1

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int rangeBitwiseAnd(int left, int right) {
// Your code goes here
}
};
 
Test Case

Input:

Left
Right