我在上次面试中遇到的一个问题是:

设计函数f,使得:f(f(n))==-n其中n是32位有符号整数;你不能用复数算术。如果你不能为整个数字范围设计这样的函数,那么就尽可能为最大范围设计它。

有什么想法吗?


当前回答

int f(int x){
    if (x < 0)
        return x;
    return ~x+1; //two's complement
}

其他回答

好问题!

这花了我大约35秒的时间思考并写下:

int f(int n){
    static int originalN=0;
    if (n!=0)
        originalN=n;
    return n-originalN;
}

这个怎么样(C语言):

int f(int n)
{
    static int t = 1;
    return (t = t ? 0 : 1) ? -n : n;
}

刚刚试过,而且

f(f(1000)) 

回报-1000

f(f(-1000)) 

返回1000

这是正确的还是我没有抓住重点?

f(n) { return -1 * abs(n) }

如何处理溢出问题?还是我错过了重点?

以下情况如何:

int f (int n)
{
    static bool pass = false;
    pass = !pass;
    return pass? n : -n;
}
#include <cmath>

int f(int n)
{
    static int count = 0;
    return ::cos(M_PI * count++) * n;
}