# Bitwise OR (or - ) of a range in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two integer values a and b. And our task is to find the bitwise OR (|) 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 − 15

Explanation − 3 | 4 | 5 | 6 | 7 | 8 = 15

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

More effective Solution,

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

Step 1 − Find the MSB bit for both a and b, let’s say them MSBa and MSBb.

Step 2 − Check if MSBa is equal to MSBb.

Step 2.1 − if MSBa and MSBb are equal. Do,

Step 2.1.1 − Set the MSB of results as 1.

Step 2.1.2 − Subtract the MSB from a and b which will be the new value for a and b. Go to step 1.

Step 2.2 − If MSBa and MSBb are equal. Do,

Step 2.2.1 − Set all bits from 0 to max(MSBa, MSBb) of the result.

Step 3 − Print result.

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

Example − a = 3 and b = 8.

Solution

Step1 − MSBa = 1 ; MSBb = 3

Step2 − MSBa != MSBb, set all bits from bit position 3 to bit position 0 of result to 1. result = (1111)2 = 15.

## Example

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

Live Demo

#include <iostream>
using namespace std;
int FindpositionMSB(long long int n){
int MSBval = -1;
while (n) {
n = n>>1;
MSBval++;
}
return MSBval;
}
long int CalcBitwiseORRaneg( long int a, long int b) {
long int result = 0;
int msba = FindpositionMSB(a);
int msbb = FindpositionMSB(b);
while (msba == msbb) {
long int value = (1 << msba);
result += value;
a -= value;
b -= value;
msba = FindpositionMSB(a);
msbb = FindpositionMSB(b);
}
msba = max(msba, msbb);
for (int i = msba; i >= 0; i--) {
long int res_val = (1<<i);
result += res_val;
}
return result;
}
int main() {
long int a = 3, b = 8;
cout<<"The bitwise OR (|) of all integers in the range from "<<a<<" to "<<b<<" is "<<CalcBitwiseORRaneg(a, b);
return 0;
}

## Output

The bitwise OR (|) of all integers in the range from 3 to 8 is 15