Not able to get the correct solution.. HELP ME!

package assignmnets;

import java.util.Scanner;

public class XOR_MaximumProfit {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	Scanner scn = new Scanner(System.in);
	int n1 = scn.nextInt();
	int n2 = scn.nextInt();
	int pos = 0;
	int temp = n2;
	while (temp > 0) {

		pos++;
		temp = temp >> 1;
	}
	pos--;

// System.out.println(pos);
long max_Xor = 0;
long xr = 0;
long num = (n2 - n1) + 1;
int vis = 0;
int shift = 0;
for (long i = 0; i < num; i++) {
int f_bit = getIthBit(n1, pos);
int s_bit = getIthBit(n2, pos);
xr = (f_bit ^ s_bit);
if (xr >= 1) {
max_Xor |= (1 << pos) & (~(0));
}
if (xr == 0 && vis != 0) {
if (f_bit == 0) {
int temp1 = set_Bit(n1, pos);
if (temp1 > n1 && temp1 <= n2) {
n1=temp1;
max_Xor |= (1 << pos) & (~(0));
}
}
if (s_bit == 1) {
int temp2 = set_Bit(n2, pos);
if (temp2 < n2 && temp2 >= n1) {
n2=temp2;
max_Xor |= (1 << pos) & (~(0));

				}
			}
		}
		pos--;
		vis++;

	}
	System.out.println(max_Xor);
}

private static int set_Bit(int n1, int pos) {
	// TODO Auto-generated method stub
	int mask = (1 << pos);
	return (n1 | pos);
}

public static int getIthBit(int n, int i) {
	int mask = (1 << i);
	return (n & mask);
}

}

@guptadev354,

Suggested approach:

  • A simple solution is to generate all pairs, find their XOR values and finally return the maximum XOR value.

  • An efficient solution is to consider pattern of binary values from L to R.
    We can see that first bit from L to R either changes from 0 to 1 or it stays 1 i.e. if we take the XOR of any two numbers for maximum value their first bit will be fixed which will be same as first bit of XOR of L and R itself. After observing the technique to get first bit, we can see that if we XOR L and R, the most significant bit of this XOR will tell us the maximum value we can achieve i.e. let XOR of L and R is 1xxx where x can be 0 or 1 then maximum XOR value we can get is 1111 because from L to R we have all possible combination of xxx and it is always possible to choose these bits in such a way from two numbers such that their XOR becomes all 1.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

@guptadev354,
What problem are you facing?