Maximizing XOR Discussions | Algorithms | HackerRank
  • + 3 comments

    Although your code is O(1), any O(b) solution will be of the same complexity or perhaps even faster for cases where b < 4. Here b is the index of MSB in a^b.

    A very simple O(b) solution that will work for any values of L & R and will work faster than above code for cases where b < 4

    int maxXor(int a, int b) {
        int value = a ^ b, result = 1;
        while (value) {
            value = value >> 1;
            result = result << 1;
        }
        return result - 1;
    }