Bitwise and (or &) of a range in C++

In this problem, we are given two integer values a and b. And our task is to find the bitwise and (&) of range from a to b. This means we will have to find the value of a & a+1 & a+2 & … b-1 & b.

Let’s take an example to understand the problem,

Input − a = 3 , b = 8

Output − 0

Explanation3 & 4 & 5 & 6 & 7 & 8 = 0

To solve the problem, a simple solution is starting from a and find bitwise and of all numbers by increasing one to b.

More effective Solution,

This is a more effective solution, this can be done using −

Step1 − Flip LSB of b.

Step2 − Compare the number with a and b, check if it is in range,

Step 2.1 − if the number is greater than a flip its LSB gain.

Step 2.2 − if it is not greater than a then number = result.

Now, let’s see the algorithm above in working −

Example − a = 3 and b = 8.

Solution

Step1 − b = 8 (1000), flipping LSB which is the only one in the number. The number becomes 0000 i.e. 0

Step2 − 0 is less than 3, 0 is the result.

Example

Now, let’s see the code to solve the problem,

Live Demo

#include <stdio.h>
int main(){
long a, b;
a = 3; b = 8;
do{
b -= (b & -b);
}while(a < b);
printf("%li", b);
}

Output

0

Updated on: 05-Aug-2020

92 Views