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

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

    How about:

    f(n) = sign(n) - (-1)n * n

    In Python:

    def f(n): 
        if n == 0: return 0
        if n >= 0:
            if n % 2 == 1: 
                return n + 1
            else: 
                return -1 * (n - 1)
        else:
            if n % 2 == 1:
                return n - 1
            else:
                return -1 * (n + 1)
    

    Python automatically promotes integers to arbitrary length longs. In other languages the largest positive integer will overflow, so it will work for all integers except that one.


    To make it work for real numbers you need to replace the n in (-1)n with { ceiling(n) if n>0; floor(n) if n<0 }.

    In C# (works for any double, except in overflow situations):

    static double F(double n)
    {
        if (n == 0) return 0;
    
        if (n < 0)
            return ((long)Math.Ceiling(n) % 2 == 0) ? (n + 1) : (-1 * (n - 1));
        else
            return ((long)Math.Floor(n) % 2 == 0) ? (n - 1) : (-1 * (n + 1));
    }
    

提交回复
热议问题