我上次面试时遇到的一个问题:
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 自动将整数提升为任意长度的 long.在其他语言中,最大的正整数会溢出,因此它适用于除那个之外的所有整数.
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.
要使其适用于实数,您需要将 (-1)n 中的 n 替换为 { ceiling(n) if n>0;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# 中(适用于任何双精度,溢出情况除外):
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)); }