Search code examples
calgorithmbit-manipulationxorbitwise-xor

Given two integers find a third integer which is different from the given two without using if statment


The question as mentioned above is as follows: Given two integers, x1 and x2, find another integer, x3, which is different from both x1 and x2 , without using the if keyword.

My solution is based on bit wise operations on integers plus on the fact that XOR between two bits will return 1 if and only if the two bits are not equal.

Is this solution valid ? Can you find a better solution ? Off course that run time considerations and memory consumption should be as good as possible.

Note: The ternary operations and comparisons(i.e. - != , == ) are as well NOT allowed

Thanks in advance,

Guy.

My solution:

int foo(int x1,int x2)
{
    // xor
    int x3 = x1 ^ x2;

    // another xor 
    x3 = x3 ^ x2;

    // not
    x3 = ~x3;

    return x3;  

}

Solution

  • Converting my comments to an answer:

    What you have is ~(x ^ y ^ y), which is just ~x, so it doesn’t work if y = ~x. One option instead is to make a number that’s different from x1 in the twos position and different from x2 in the ones position:

    return ~(x1 & 2 | x2 & 1);
    

    (Simplification from (~x1 & 2) | (~x2 & 1) credit to @chux. Thanks!)