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
def MSBPosition ( N ) : NEW_LINE INDENT msb_p = - 1 NEW_LINE while ( N ) : NEW_LINE INDENT N = N >> 1 NEW_LINE msb_p += 1 NEW_LINE DEDENT return msb_p NEW_LINE DEDENT def findBitwiseOR ( L , R ) : NEW_LINE INDENT res = 0 NEW_LINE msb_p1 = MSBPosition ( L ) NEW_LINE msb_p2 = MSBPosition ( R ) NEW_LINE while ( msb_p1 == msb_p2 ) : NEW_LINE INDENT res_val = ( 1 << msb_p1 ) NEW_LINE res += res_val NEW_LINE L -= res_val NEW_LINE R -= res_val NEW_LINE msb_p1 = MSBPosition ( L ) NEW_LINE msb_p2 = MSBPosition ( R ) NEW_LINE DEDENT msb_p1 = max ( msb_p1 , msb_p2 ) NEW_LINE for i in range ( msb_p1 , - 1 , - 1 ) : NEW_LINE INDENT res_val = ( 1 << i ) NEW_LINE res += res_val NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L , R = 12 , 18 NEW_LINE print ( findBitwiseOR ( L , R ) ) NEW_LINE DEDENT