Maximum Bitwise OR pair from a range | C ++ implementation of the approach ; Function to return the maximum bitwise OR possible among all the possible pairs ; If there is only a single value in the range [ L , R ] ; Loop through each bit from MSB to LSB ; MSBs where the bits differ , all bits from that bit are set ; If MSBs are same , then ans bit is same as that of bit of right or left limit ; Driver code
#include <iostream> NEW_LINE using namespace std ; const int MAX = 64 ; int maxOR ( int L , int R ) { if ( L == R ) { return L ; } int ans = 0 ; for ( int i = MAX - 1 ; i >= 0 ; i -- ) { int p , lbit , rbit ; p = 1 << i ; if ( ( rbit == 1 ) && ( lbit == 0 ) ) { ans += ( p << 1 ) - 1 ; break ; } if ( rbit == 1 ) { ans += p ; } } return ans ; } int main ( ) { int L = 4 , R = 5 ; cout << maxOR ( L , R ) ; return 0 ; }