Xor profit problem

#include
using namespace std;
int main(){
int x , y;
int m = 0;

cin>>x>>y;
int k = 0;

for(int i = x , j = y;i<=y && j>=x; j-- , i++){
k=m;
m = (i^j);

if(m>k){
  k=m;
  
}

}
cout<<k;

}

when given explanation test cases giving right output but failing test cases whats the problem in code ??

You’re not using the correct format

int main() {
    int m, n, mx=-100000;
    cin >> m >> n;
    for(int i=m; i<=n; ++i) {
        for(int j=m+1; j<=n; ++j) {
            if(mx < (i^j)) mx=i^j;
        }
    }
    cout<<mx;
}
1 Like

https://online.codingblocks.com/player/5562/content/772?s=1136

how to do this question?
i am computing xor between all the pairs one by one which is taking two loops, is there any other way

See my code it is passing given testcass but it is not passing when submitted I think i should remove m=k in my code hope it helps

Passed Successfully
:wink: :100:
O(N) SOLUTION

#include<bits/stdc++.h>
using namespace std;
int main () {
	int a,b; cin>>a>>b;
	int xor_max = a^b;
	int i = 32;
	while(i>=0)
	{
		int a = (1<<i);
		if(xor_max & (a))
			break;
		i--;
	}
	i++;
	int ans = (1<<i);
	cout<<ans-1;
	return 0;
}
2 Likes

No we can compute this in different ways also with O(N) SOLUTION

The right answer is

#include
using namespace std;
int main(){
int a,b;
cin>>a>>b;
int xr = a^b;
int msbpos=0;
while(xr){
msbpos++;
xr = xr>>1;
}
int maxxr=0;
int x=1;
while(msbpos–){
maxxr+=x;
x = x<<1;
}

cout<<maxxr;

}

this code will pass all the test cases and its with proper commnents
#include
using namespace std;
int maxRange(int x, int y){
//get xor of the nos given
int XOR=x^y;
//now find the most significant bit position in the xor
int msbPOS=0;//most significant bit position
while(XOR!=0){
msbPOS++;
XOR = XOR>>1;
}
//now construct result by adding 1 msbpos times
int maxXOR = 0;
int two =1;
while(msbPOS!=0){
maxXOR +=two;
two= two<<1;
msbPOS–;
}
return maxXOR;

}
int main() {
int x,y;
cin>>x>>y;
cout<<maxRange(x,y)<<endl;
return 0;
}

1 Like

hey bro, can u please explain this code. I am newbie . :pleading_face: :pleading_face: