Maximizing XOR Discussions | Algorithms | HackerRank
  • + 0 comments

    My way had the same concept as your picture: to calculate the highest order bit that is different and subtract one from it, though my way has a loop that you avoided by doing an ^.

    static int maxXor(int l, int r) {
            int lBit = Integer.highestOneBit(l);
            int rBit = Integer.highestOneBit(r);
            if (lBit == rBit) {
                if (lBit == 0) {
                    return 0;
                } else {
                    int newL = l & (~lBit);
                    int newR = r & (~lBit);
                    return maxXor(newL, newR);
                }
            } else {
                int max = Math.max(lBit, rBit);
                return (max << 1) -1;
            }
        }