Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;  

}
like image 959
Guy Avraham Avatar asked Feb 18 '17 08:02

Guy Avraham


2 Answers

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!)

like image 139
Ry- Avatar answered Nov 15 '22 05:11

Ry-


Being pedantic, since they said no if keyword then ternaries should be fair game...

return (x1+1 == x2) ? x1+2 : x1+1;

Of course, maybe that's cheating. No problem, here's a ternary-free version:

return x1+1+(x1+1==x2);

And don't worry, if you think the conditional is still cheating, there are many ways to implement it with straight bit manipulation.

Note that the addition solution is really only valid for unsigned integers, since it induces the potential for signed overflow (which is UB). If this is a concern, you can replace the addition with another operation (for example, x1^(1+(x1^1==x2)).

like image 35
nneonneo Avatar answered Nov 15 '22 06:11

nneonneo