A question I got on my last interview:
Design a function
f, such that:f(f(n)) == -nWhere
n<
A C++ version, probably bending the rules somewhat but works for all numeric types (floats, ints, doubles) and even class types that overload the unary minus:
template
struct f_result
{
T value;
};
template
f_result f (T n)
{
f_result result = {n};
return result;
}
template
T f (f_result n)
{
return -n.value;
}
void main (void)
{
int n = 45;
cout << "f(f(" << n << ")) = " << f(f(n)) << endl;
float p = 3.14f;
cout << "f(f(" << p << ")) = " << f(f(p)) << endl;
}