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

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

    This Perl solution works for integers, floats, and strings.

    sub f {
        my $n = shift;
        return ref($n) ? -$$n : \$n;
    }
    

    Try some test data.

    print $_, ' ', f(f($_)), "\n" for -2, 0, 1, 1.1, -3.3, 'foo' '-bar';
    

    Output:

    -2 2
    0 0
    1 -1
    1.1 -1.1
    -3.3 3.3
    foo -foo
    -bar +bar
    

提交回复
热议问题