Maximum possible Bitwise OR of the two numbers from the range [ L , R ] | Function to return the maximum bitwise OR of any pair from the given range ; Converting L to its binary representation ; Converting R to its binary representation ; In order to make the number of bits of L and R same ; Push 0 to the MSB ; When ith bit of R is 1 and ith bit of L is 0 ; From MSB side set all bits of L to be 1 ; From ( i + 1 ) th bit , all bits of L changed to be 1 ; Driver code
def max_bitwise_or ( L , R ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE v3 = [ ] NEW_LINE z = 0 NEW_LINE i = 0 NEW_LINE ans = 0 NEW_LINE cnt = 1 NEW_LINE while ( L > 0 ) : NEW_LINE INDENT v1 . append ( L % 2 ) NEW_LINE L = L // 2 NEW_LINE DEDENT while ( R > 0 ) : NEW_LINE INDENT v2 . append ( R % 2 ) NEW_LINE R = R // 2 NEW_LINE DEDENT while ( len ( v1 ) != len ( v2 ) ) : NEW_LINE INDENT v1 . append ( 0 ) NEW_LINE DEDENT for i in range ( len ( v2 ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( v2 [ i ] == 1 and v1 [ i ] == 0 and z == 0 ) : NEW_LINE INDENT z = 1 NEW_LINE continue NEW_LINE DEDENT if ( z == 1 ) : NEW_LINE INDENT v1 [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( len ( v2 ) ) : NEW_LINE INDENT v3 . append ( v2 [ i ] v1 [ i ] ) NEW_LINE DEDENT for i in range ( len ( v2 ) ) : NEW_LINE INDENT if ( v3 [ i ] == 1 ) : NEW_LINE INDENT ans += cnt NEW_LINE DEDENT cnt *= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT L = 10 NEW_LINE R = 20 NEW_LINE print ( max_bitwise_or ( L , R ) ) NEW_LINE