Maximizing XOR Discussions | Algorithms | HackerRank
  • + 0 comments

    We can also do -

    static int maximizingXor(int l, int r) {
            int xored  = l ^ r;
            int highestBit = Integer.highestOneBit(xored);
            return 2*highestBit -1;   
     }
    

    The logic is same. One additional charactersitics that's been used is:- Sum of all the trailing zeros converted to ones is HighestBit - 1.

    For eg - L = 10111
    R = 11100 _X___ <-- that's most significant differing bit 01000 <-- This is what HighestBit gave us.

    We need to calculate 01111 in int, this can be obtained by sum of 01000 and 00111 and that's equal to 2*highestBit - 1.