给定范围[L,R],我们需要找到此范围内的两个整数,以使它们的XOR在两个整数的所有可能选择中最大
如果给定范围为L = 1且R = 21,则输出将为31,因为− 31是15和16的XOR,并且在范围内最大。
1. Calculate the (L^R) value 2. From most significant bit of this value add all 1s to get the final result
#include <bits/stdc++.h>
using namespace std;
int getMaxXOR(int L, int R){
int LXR = L ^ R;
int msbPos = 0;
while (LXR) {
msbPos++;
LXR >>= 1;
}
int maxXOR = 0;
int two = 1;
while (msbPos--) {
maxXOR += two;
two <<= 1;
}
return maxXOR;
}
int main(){
int L = 1;
int R = 21;
cout << "Result = " << getMaxXOR(L, R) << endl;
return 0;
}输出结果
当您编译并执行上述程序时。它生成以下输出-
Result = 31