Designing function f(f(n)) == -n

前端 未结 30 2829
清酒与你
清酒与你 2020-12-02 03:32

A question I got on my last interview:

Design a function f, such that:

f(f(n)) == -n

Where n<

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 03:42

    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;
    }
    

提交回复
热议问题