设计函数f(f(n))== - n [英] Designing function f(f(n)) == -n
问题描述
我上次采访时遇到的问题:
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));
}
这篇关于设计函数f(f(n))== - n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!