我在上次面试中遇到的一个问题是:
设计函数f,使得:f(f(n))==-n其中n是32位有符号整数;你不能用复数算术。如果你不能为整个数字范围设计这样的函数,那么就尽可能为最大范围设计它。
有什么想法吗?
我在上次面试中遇到的一个问题是:
设计函数f,使得:f(f(n))==-n其中n是32位有符号整数;你不能用复数算术。如果你不能为整个数字范围设计这样的函数,那么就尽可能为最大范围设计它。
有什么想法吗?
当前回答
一个C++版本,可能会稍微改变规则,但适用于所有数值类型(浮点、整型、双精度),甚至是重载一元负号的类类型:
template <class T>
struct f_result
{
T value;
};
template <class T>
f_result <T> f (T n)
{
f_result <T> result = {n};
return result;
}
template <class T>
T f (f_result <T> n)
{
return -n.value;
}
void main (void)
{
int n = 45;
cout << "f(f(" << n << ")) = " << f(f(n)) << endl;
float p = 3.14f;
cout << "f(f(" << p << ")) = " << f(f(p)) << endl;
}
其他回答
另一种利用短路的Javascript解决方案。
function f(n) {return n.inv || {inv:-n}}
f(f(1)) => -1
f(f(-1)) => 1
#include <cmath>
int f(int n)
{
static int count = 0;
return ::cos(M_PI * count++) * n;
}
有些类似,但我只是想写下我的第一个想法(用C++)
#include <vector>
vector<int>* f(int n)
{
returnVector = new vector<int>();
returnVector->push_back(n);
return returnVector;
}
int f(vector<int>* n) { return -(n->at(0)); }
仅使用重载使f(f(n))实际调用两个不同的函数
int f( int n ){
return n==0?0:(n&1?n:-n)+(n<0?-1:1);
}
这个怎么样:
do
local function makeFunc()
local var
return function(x)
if x == true then
return -var
else
var = x
return true
end
end
end
f = makeFunc()
end
print(f(f(20000)))