原题:
Claris loves bitwise operations very much, especially XOR, because it has many beautiful features. He gets four positive integers a,b,c,da,b,c,d that satisfies a≤ba≤b and c≤dc≤d. He wants to choose two integers x,yx,y that satisfies a≤x≤ba≤x≤b and c≤y≤dc≤y≤d, and maximize the value of x XOR yx XOR y. But he doesn’t know how to do it, so please tell him the maximum value of x XOR yx XOR y.
Input
The first line contains an integer T(1≤T≤10,000)T(1≤T≤10,000)——The number of the test cases.
For each test case, the only line contains four integers a,b,c,d(1≤a,b,c,d≤1018)a,b,c,d(1≤a,b,c,d≤1018). Between each two adjacent integers there is a white space separated.
Output
For each test case, the only line contains a integer that is the maximum value of x XOR yx XOR y.
Sample Input
2
1 2 3 4
5 7 13 15
Sample Output
6
11
Hint
In the first test case, when and only when
x
=
2
,
y
=
4
x=2,y=4
x=2,y=4, the value of
x
X
O
R
y
x~XOR~y
x XOR y is the maximum.
In the second test case, when and only when
x
=
5
,
y
=
14
x=5,y=14
x=5,y=14 or
x
=
6
,
y
=
13
x=6,y=13
x=6,y=13, the value of
x
X
O
R
y
x~XOR~y
x XOR y is the maximum.
题意:
有四个数a,b,c,d。满足a<b和c<d。现在从ab之间找一值x,在cd之间找一值y。问其x异或y的最大值是多少。
题解:
这道题是有关二进制的题目,本人对于二进制了解尚浅,只能在此浅谈。
我们从二进制的角度出发,我要使数值最大,是不是最高位越大越高(即第一个1所在的位置)。这样我们就可以去寻找了,如果两个数x,y所在范围可以在二进制存储格式下的一个位置x,y都可以取0或者1,那么此位置一定可以取1。如果x,y在这一位并不是0,1都能取,那么由于要使得答案的这一位等于1,也只有唯一的取法。
对于xy范围之外的位置,由于范围已经取定,所以后边的位置都是已经确定的。
附上AC代码:
#include<iostream>
using namespace std;
typedef long long LL;
int main()
{
LL t,a,b,c,d;
cin>>t;
while(t--){
cin>>a>>b>>c>>d;
LL x = 0;
LL i = 1;
i <<= 60;//初始化向右移60位差不多刚好大于10^18次方后面方法类似于二分答案
for(;i;i = i>>1)//每一次都向左移一位
{
if(b >= i && c < i)
{
x += i;
b -= i;
if(a >= i) a -= i;
else a = 0;
}
else if(d >= i)
{
x += i;
d -= i;
if(c >= i) c -= i;
else c = 0;
if(a >= i)
{
x -= i;
a -= i;
b -= i;
}
}
}
cout<<x<<endl;
}
return 0;
}