我上次采访时遇到的问题:
A question I got on my last interview:
设计函数 f ,这样: f(f(n)) == -n
其中 n 是32位有符号整数;你不能使用复数运算。
Where n is a 32 bit signed integer; you can't use complex numbers arithmetic.
如果你不能为整个数字范围设计这样的函数,那就设计一个最大范围的算法。
If you can't design such a function for the whole range of numbers, design it for the largest range possible.
任何想法?
推荐答案关于:
f(n) = sign(n) - (-1)n * n在Python中:
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自动将整数提升为任意长度的长度。在其他语言中,最大的正整数将溢出,因此它将适用于除了那个之外的所有整数。
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.
使其成为可能如果n> 0,则需要用 {ceiling(n)替换(-1) n 中的 n 。 floor(n)如果n< 0} 。
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 }.
在C#中(适用于任何double,除了溢出情况):
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)); }