Friday, 17 October 2014

Max XOR of two numbers

Question:Suppose we're given two numbers l and r and that we want to find max(ij) for li,jr.

Answer:
Common solution is to proceed with O(n^2) time.

but, It is possible to do it in O(log r) time.
The maximum possible XOR of any two integers from an interval [l,r] can be determined from lr, assuming l,r to be integers. This value is equal to 2p1, where p is the smallest value such that 2p is larger than lr.
Here is an implementation in C++
int maximumXOR(int l, int r) {
    int q = l ^ r, a = 1;
    while(q){
        q /= 2;
        a <<= 1;
    }
    return --a;
}

No comments:

Post a Comment