Dev102.com has been running a series of weekly “programming job interview challenges”. This week’s challenge (#4) was a bit too easy I think, this is my go at a solution in C#.

The question was: “How would you implement the following method: Foo(7) = 17 and Foo(17) = 7. Any other input to that method is not defined so you can return anything you want. Just follow these rules”:

Conditional statements (if, switch, …) are not allowed.
Usage of containers (hash tables, arrays, …) are not allowed.

This can be solved with some surprisingly simple bit-twiddling:

public int Foo(int number)
{
   return number ^ 22;
}

A similar but “costlier” solution than xor 22 is:

public int Foo(int number)
{
   return (number + 10) % 20;
}
Advertisements