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
function max_bitwise_or ( L , R ) { let v1 = [ ] , v2 = [ ] , v3 = [ ] ; let z = 0 , i , ans = 0 , cnt = 1 ; while ( L > 0 ) { v1 . push ( L % 2 ) ; L = parseInt ( L / 2 ) ; } while ( R > 0 ) { v2 . push ( R % 2 ) ; R = parseInt ( R / 2 ) ; } while ( v1 . length != v2 . length ) { v1 . push ( 0 ) ; } for ( i = v2 . length - 1 ; i >= 0 ; i -- ) { if ( v2 [ i ] == 1 && v1 [ i ] == 0 && z == 0 ) { z = 1 ; continue ; } if ( z == 1 ) { v1 [ i ] = 1 ; } } for ( i = 0 ; i < v2 . length ; i ++ ) { v3 . push ( v2 [ i ] v1 [ i ] ) ; } for ( i = 0 ; i < v2 . length ; i ++ ) { if ( v3 [ i ] == 1 ) { ans += cnt ; } cnt *= 2 ; } return ans ; } let L = 10 , R = 20 ; document . write ( max_bitwise_or ( L , R ) ) ;