is there any better approach to this problem?
i tried this code-
XOR profit problem
@rockstarpkm yes , we can optimize it and do it in log(n) complexity.
For any two numbers, we first find there first set bit from left, now, we can always be sure that this bit will be set in answer also, cause if we unset this than value will decrease and we would not be able to compensate for this even if all the following bits would be set to 1.
Now once we have found the first set bit, now we can always have a combination of two numbers that will be such that rest of the bits become 1.
int maxXORInRange(int L, int R)
{
// get xor of limits
int LXR = L ^ R;
// loop to get msb position of L^R
int msbPos = 0;
while (LXR)
{
msbPos++;
LXR >>= 1;
}
// construct result by adding 1,
// msbPos times
int maxXOR = 0;
int two = 1;
while (msbPos--)
{
maxXOR += two;
two <<= 1;
}
```
If this resolves yoyr doubt mark it as resolved.
what will we return from this function?
@rockstarpkm sorry forgot to write last line.
We will return maxXor.
If this resolves your doubt mark it as resolved.
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.