Maximizing XOR Discussions | Algorithms | HackerRank

Sort by

recency

|

496 Discussions

|

  • + 0 comments

    Here is my easy and straitghforward solution, you can watch video here : https://youtu.be/pCU8W_ofvDg

    int maximizingXor(int l, int r) {
        int result = 0;
        for(int a = l; a <= r; a++){
            for(int b = a; b<= r; b++){
                result = max(result, a ^ b);
            }
        }
        return result;
    }
    
  • + 0 comments
    def maximizingXor(l, r):
        m=0
        for i in range(l,r+1):
            for j in range(l,r+1):
                if(m>(i^j)):
                    pass
                else:
                    m=i^j
        return m
    
  • + 0 comments

    I optimized XOR maximization algorithm reduces complexity from O(log r) to O(log l) by iterating only over the smaller number L. It uses bitwise comparison to maximize the XOR value, flipping bits of l or r as needed while respecting the range [L,R] . The final XOR result is calculated using a fast power function, ensuring minimal operations and efficiency. This method ensures the maximum XOR value is computed while preserving the range constraints.

    code with more detalied explain: https://github.com/MohamedHussienMansour/Maximum-XOR-problem-with-O-log-L-

  • + 0 comments

    Lots of naive solutions in the comments. Here is a Python solution:

    def maximizingXor(l, r):
        count = 0
        while r != l:
            r >>= 1
            l >>= 1
            count += 1
        return (1 << count) - 1
    
  • + 0 comments

    Here is my Python solution!

    def binary(num):
        remainders = []
        while num != 0 :
            remainders.insert(0, str(num % 2))
            num //= 2
        return "".join(remainders)
    
    def xor(num1, num2):
        newnum = []
        if len(num1) > len(num2):
            num2 = (len(num1) - len(num2)) * "0" + num2
        elif len(num2) > len(num1):
            num1 = (len(num2) - len(num1)) * "0" + num1
        for i in range(len(num1)):
            if num1[i] == num2[i]:
                newnum.append("0")
            else:
                newnum.append("1")
        return "".join(newnum)
    
    def decimal(num):
        newnum = 0
        for i in range(len(num)):
            newnum += int(num[-i - 1]) * 2 ** i
        return newnum
    
    def maximizingXor(l, r):
        values = []
        for num1 in range(l, r + 1):
            for num2 in range(num1 + 1, r + 1):
                values.append(decimal(xor(binary(num1), binary(num2))))
        return max(values)