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

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

    Nobody said it had to be stateless.

    int32 f(int32 x) {
        static bool idempotent = false;
        if (!idempotent) {
            idempotent = true;
            return -x;
        } else {
            return x;
        }
    }
    

    Cheating, but not as much as a lot of the examples. Even more evil would be to peek up the stack to see if your caller's address is &f, but this is going to be more portable (although not thread safe... the thread-safe version would use TLS). Even more evil:

    int32 f (int32 x) {
        static int32 answer = -x;
        return answer;
    }
    

    Of course, neither of these works too well for the case of MIN_INT32, but there is precious little you can do about that unless you are allowed to return a wider type.

提交回复
热议问题