Maximum XOR value of a pair from a range | Java program to get maximum xor value of two numbers in a range ; method to get maximum xor value in range [ L , R ] ; get xor of limits ; loop to get msb position of L ^ R ; construct result by adding 1 , msbPos times ; main function
class Xor { static int maxXORInRange ( int L , int R ) { int LXR = L ^ R ; int msbPos = 0 ; while ( LXR > 0 ) { msbPos ++ ; LXR >>= 1 ; } int maxXOR = 0 ; int two = 1 ; while ( msbPos -- > 0 ) { maxXOR += two ; two <<= 1 ; } return maxXOR ; } public static void main ( String [ ] args ) { int L = 8 ; int R = 20 ; System . out . println ( maxXORInRange ( L , R ) ) ; } }