我在上次面试中遇到的一个问题是:
设计函数f,使得:f(f(n))==-n其中n是32位有符号整数;你不能用复数算术。如果你不能为整个数字范围设计这样的函数,那么就尽可能为最大范围设计它。
有什么想法吗?
我在上次面试中遇到的一个问题是:
设计函数f,使得:f(f(n))==-n其中n是32位有符号整数;你不能用复数算术。如果你不能为整个数字范围设计这样的函数,那么就尽可能为最大范围设计它。
有什么想法吗?
当前回答
int f(const int n) {
static int last_n;
if (n == 0)
return 0;
else if (n == last_n)
return -n;
else
{
last_n = n;
return n;
}
}
哈克,但正确。
其他回答
记住你的上一个状态不是一个足够好的答案吗?
int f (int n)
{
//if count
static int count = 0;
if (count == 0)
{
count = 1;
return n;
}
if (n == 0)
return 0;
else if (n > 0)
{
count = 0;
return abs(n)*(-1);
}
else
{
count = 0;
return abs(n);
}
}
int main()
{
int n = 42;
std::cout << f(f(n))
}
C函数:
int f(int n) /* Treats numbers in the range 0XC0000000 to 0X3FFFFFFF as valid to
generate f(f(x)) equal to -x. If n is within this range, it will
project n outside the range. If n is outside the range, it will
return the opposite of the number whose image is n. */
{
return n ? n > 0 ? n <= 0X3FFFFFFF ? 0X3FFFFFFF + n : 0X3FFFFFFF - n :\
n >= 0XC0000000 ? 0XC0000000 + n : 0XC0000000 - n : 0;
}
Ideone测试和下载链接
另一种利用短路的Javascript解决方案。
function f(n) {return n.inv || {inv:-n}}
f(f(1)) => -1
f(f(-1)) => 1
Java脚本
function f(n) {
return typeof n === "number" ?
function() {return -n} :
n();
}
少于50个字符(C#)
int f(int n) { return (n <= 0) ? n : f(-n); }
或更容易阅读:
static int f(int n) {
if (n <= 0)
return n;
else
return f(-n);
}
要测试
static void Main(string[] args) {
for (int n = int.MinValue; n < int.MaxValue; n+=1) {
Console.Out.WriteLine("Value: " + n + " Result: " + f(f(n)));
}
}
它有效(假设我正确理解问题)