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

前端 未结 30 2821
清酒与你
清酒与你 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:38

    The question doesn't say anything about what the input type and return value of the function f have to be (at least not the way you've presented it)...

    ...just that when n is a 32-bit integer then f(f(n)) = -n

    So, how about something like

    Int64 f(Int64 n)
    {
        return(n > Int32.MaxValue ? 
            -(n - 4L * Int32.MaxValue):
            n + 4L * Int32.MaxValue);
    }
    

    If n is a 32-bit integer then the statement f(f(n)) == -n will be true.

    Obviously, this approach could be extended to work for an even wider range of numbers...

提交回复
热议问题