TITLE: A function such that $f(f(n)) = -n$?
QUESTION [11 upvotes]: This question from somebody's job interview made me puzzled:
Design a function f, such that:
$f(f(n)) = -n$ ,
where n is a 32 bit signed integer; you can't use complex numbers arithmetic. If you can't design such a function for the whole range of numbers, design it for the largest range possible.
Do you have any idea how to tackle it?
EDIT: I removed "Real number" from the title, since it just confused readers, but it was meant just to stress that complex numbers are not allowed.

REPLY [2 votes]: Here's a quirky solution (I believe that it's what Hurkyl meant by "bit-tiwddling"): The fact that we are working with 32-bit signed integers means that $x+2^{32}=-x$. This is because the number is represented by the computer in binary, the "most significant" bit is used to determine its sign, and overflow is discarded. Explicitly, if $x\geq 0$ then the $32^\text{nd}$ binary digit is a zero and so adding $2^{32}$ flips it to a one. If $x<0$ then the $32^\text{nd}$ binary digit is a one, so adding $2^{32}$ flips it to zero, and the carry-over one is ignored.
Therefore, we can consider the function
$$f(n)=n+2^{31}.$$
Applying this twice clearly gives $f(f(n))=n+2^{32}$, which is the same thing as $-n$.
(Actually, there is one edge case: the number $"\!\!-0\!\!"\,=0+2^{32}$ is actually interpreted as $-2^{31}$. So if $n=-2^{31}$, then $n+2^{32}=0$, and indeed $-x=2^{31}$ is not expressible in the 32-bit signed format, so we'll have to let this one go. In fact, it seems likely to me that this this was the "point" of the question from the interviewer's perspective: not that you could build some random function, but that you could recognize the inherent limitations of the architecture.)