Bitwise OR ( or | ) of a range | 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
function MSBPosition ( N ) { let msb_p = - 1 ; while ( N > 0 ) { N = N >> 1 ; msb_p ++ ; } return msb_p ; } function findBitwiseOR ( L , R ) { let res = 0 ; let msb_p1 = MSBPosition ( L ) ; let msb_p2 = MSBPosition ( R ) ; while ( msb_p1 == msb_p2 ) { let res_val = ( 1 << msb_p1 ) ; res += res_val ; L -= res_val ; R -= res_val ; msb_p1 = MSBPosition ( L ) ; msb_p2 = MSBPosition ( R ) ; } msb_p1 = Math . max ( msb_p1 , msb_p2 ) ; for ( let i = msb_p1 ; i >= 0 ; i -- ) { let res_val = ( 1 << i ) ; res += res_val ; } return res ; } let L = 12 , R = 18 ; document . write ( findBitwiseOR ( L , R ) ) ;