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
< ? php function MSBPosition ( $ N ) { $ msb_p = -1 ; while ( $ N ) { $ N = $ N >> 1 ; $ msb_p ++ ; } return $ msb_p ; } function findBitwiseOR ( $ L , $ R ) { $ res = 0 ; $ msb_p1 = MSBPosition ( $ L ) ; $ msb_p2 = MSBPosition ( $ R ) ; while ( $ msb_p1 == $ msb_p2 ) { $ 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 ( $ i = $ msb_p1 ; $ i >= 0 ; $ i -- ) { $ res_val = ( 1 << $ i ) ; $ res += $ res_val ; } return $ res ; } $ L = 12 ; $ R = 18 ; echo findBitwiseOR ( $ L , $ R ) ; ? >