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

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

    C# for a range of 2^32 - 1 numbers, all int32 numbers except (Int32.MinValue)

        Func f = n =>
            n < 0
               ? (n & (1 << 30)) == (1 << 30) ? (n ^ (1 << 30)) : - (n | (1 << 30))
               : (n & (1 << 30)) == (1 << 30) ? -(n ^ (1 << 30)) : (n | (1 << 30));
    
        Console.WriteLine(f(f(Int32.MinValue + 1))); // -2147483648 + 1
        for (int i = -3; i <= 3  ; i++)
            Console.WriteLine(f(f(i)));
        Console.WriteLine(f(f(Int32.MaxValue))); // 2147483647
    

    prints:

    2147483647
    3
    2
    1
    0
    -1
    -2
    -3
    -2147483647
    

提交回复
热议问题