There’s a “category” of questions that is commonly asked in large companies’ interviews that tests your thorough understanding of a certain programming language. I’ll send you an episode each time I remember one of them…
Represent x ? y : z as function int ternary(int x, int y, int z); using only ~, !, ^, &, +, |, << and >>. You’re not allowed to use -, * or if-else.
Solution 1:
int ternary(int x, int y, int z)
{
int ret[2] = {y, z};
return ret[!x];
}
The only comment here is that if x is 0, !x is 1… and if x is NOT 0, which means true in C++ as you probably know; !x is 0 – which is exactly what we want to index the array properly.
Solution 2:
int ternary(int x, int y, int z)
{
int t;
(!x && (t = z)) || (x && (t = y));
return t;
}
This one is actually important. Remember that the expression t = z (or t = y) evaluates to z (or y), and in the same time loads in t the correct value. That’s why we can depend on t in the end.
Thanks to F.M.A.R. who sent me this problem...
This is the pdf version of this article.