For two integers, find a third integer other than two without using if statment

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

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

Is this really a solution? Can you find a better solution? Of course, runtime and memory consumption should be as good as possible.

Note: triple operations and comparisons (i.e. -! =, ==) are also NOT allowed

Thanks in advance,

Guy

My decision:

int foo(int x1,int x2) { // xor int x3 = x1 ^ x2; // another xor x3 = x3 ^ x2; // not x3 = ~x3; return x3; } 
+5
source share
2 answers

Convert my comments to response:

You have ~(x ^ y ^ y) , which is just ~x , so it doesn't work if y = ~x . One option is to make a number different from x1 in two positions and different from x2 in one position:

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

(Simplification from (~x1 & 2) | (~x2 & 1) @chux loan. Thank you!)

+4
source

Being pedantic, as they said no if keyword, then the trojans should be fair play ...

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

Of course, maybe this is a hoax. No problem, there is a ternary 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 using direct bit manipulation.

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

+3
source

Source: https://habr.com/ru/post/1264377/


All Articles