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

前端 未结 30 2825
清酒与你
清酒与你 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条回答
  •  被撕碎了的回忆
    2020-12-02 03:40

    Depending on your platform, some languages allow you to keep state in the function. VB.Net, for example:

    Function f(ByVal n As Integer) As Integer
        Static flag As Integer = -1
        flag *= -1
    
        Return n * flag
    End Function
    

    IIRC, C++ allowed this as well. I suspect they're looking for a different solution though.

    Another idea is that since they didn't define the result of the first call to the function you could use odd/evenness to control whether to invert the sign:

    int f(int n)
    {
       int sign = n>=0?1:-1;
       if (abs(n)%2 == 0)
          return ((abs(n)+1)*sign * -1;
       else
          return (abs(n)-1)*sign;
    }
    

    Add one to the magnitude of all even numbers, subtract one from the magnitude of all odd numbers. The result of two calls has the same magnitude, but the one call where it's even we swap the sign. There are some cases where this won't work (-1, max or min int), but it works a lot better than anything else suggested so far.

提交回复
热议问题