Recently encountered a technical interview question, here to share. The title is to design a function f that makes
F (f (n)) =-N
Here n is a 32-bit integer. You cannot use imaginary or plural operations.
If you can't design a function to make it work for all integers under 32 bits, design this function so that it can be applied to as many integers as possible.
Design a function f, such that:
f (f (n)) = = N
Where n is a bit signed integer; can ' t use complex numbers a Rithmetic.
If you can ' t-design such a function for the whole range of numbers, it is for the largest range possible.
Try one:
For languages that support the built-in state of a function, such as the C language, it is easy to solve this face test. The following code can be:
C + +
int f (int n) {
static int state =-1;
State *=-1;
return n * state;
}
This defines a function built in state variable states. The first time the function f is executed, State equals 1, and the function returns N. The second time the function is executed, state equals-1, and the function returns-N. This solution can be applied to all 32-bit integers except int_min. For int_min, negation causes overflow, i.e. F (f (int_min)) = Int_min.
Of course, this topic should not be so easy to solve. How do you solve a language that doesn't support built-in state, such as C # or Java?
Try two:
You can use global variables to store the state. For example, the following C # code:
private static int state =-1;
public static int f (int i) {State
*=-1;
return state * i;
}
But this solution is still not perfect, it is not so.