XOR Challenge

You are given an Integer C such that the XOR of two integers (A,B) is C. In short A ⊕ B = C (⊕ denotes the bitwise XOR operation)

Out of all possible pairs of A and B, you have to find such two integers such that their product is maximum. 

Let's define L(A) = the length of A in its binary representation. Then, L(A) <= L(C) and L(B) <= L(C).

Example:

Input:  C = 13
Output: 70

Approach

Java

public class XORChallenge {

    public static void main(String[] argsthrows Exception {
        int C = 13;
        long res = xorSolve(C);
        System.out.println(res);

    }

    static long xorSolve(int c) {
        int a = 0;
        int b = 0;
        int temp = c;
        int count = 0;
        while (temp > 0) {
            count++;
            temp /= 2;
        }

        for (int i = count - 1; i > -1; i--) {
            if ((c & (1 << i)) > 0) {
                if (a > b)
                    b |= (1 << i);
                else
                    a |= (1 << i);
            } else {
                a |= (1 << i);
                b |= (1 << i);
            }
        }
        return 1l*a * b;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

long xorSolve(long c)
{
    long a = 0;
    long b = 0;
    long temp = c;
    long count = 0;
    while (temp > 0)
    {
        count++;
        temp /= 2;
    }

    for (long i = count - 1i > -1i--)
    {
        if ((c & (1 << i)) > 0)
        {
            if (a > b)
                b |= (1 << i);
            else
                a |= (1 << i);
        }
        else
        {
            a |= (1 << i);
            b |= (1 << i);
        }
    }
    return a * b;
}

int main()
{
    long C = 13;

    cout << xorSolve(C<< "\n";

    return 0;
}


No comments:

Post a Comment