Bitwise OR ( or | ) of a range | C ++ Program to find the bitwise OR of all the integers in range L - R ; Returns the Most Significant Bit Position ( MSB ) ; Returns the Bitwise OR of all integers between L and R ; Find the MSB position in L ; Find the MSB position in R ; Add this value until msb_p1 and msb_p2 are same ; ; Calculate msb_p1 and msb_p2 ; Find the max of msb_p1 and msb_p2 ; Set all the bits from msb_p1 upto 0 th bit in the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MSBPosition ( long long int N ) { int msb_p = -1 ; while ( N ) { N = N >> 1 ; msb_p ++ ; } return msb_p ; } long long int findBitwiseOR ( long long int L , long long int R ) { long long int res = 0 ; int msb_p1 = MSBPosition ( L ) ; int msb_p2 = MSBPosition ( R ) ; while ( msb_p1 == msb_p2 ) { long long int res_val = ( 1 << msb_p1 ) ; res += res_val ; L -= res_val ; R -= res_val ; msb_p1 = MSBPosition ( L ) ; msb_p2 = MSBPosition ( R ) ; } msb_p1 = max ( msb_p1 , msb_p2 ) ; for ( int i = msb_p1 ; i >= 0 ; i -- ) { long long int res_val = ( 1 << i ) ; res += res_val ; } return res ; } int main ( ) { int L = 12 , R = 18 ; cout << findBitwiseOR ( L , R ) << endl ; return 0 ; }