gpt4 book ai didi

math - 设计函数 f(f(n)) == -n

转载 作者:行者123 更新时间:2023-12-02 20:03:59 25 4
gpt4 key购买 nike

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

Design a function f, such that:

f(f(n)) == -n

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.

有什么想法吗?

最佳答案

你没有说他们期望什么样的语言......这是一个静态解决方案(Haskell)。它基本上弄乱了两个最重要的位:

f :: Int -> Int
f x | (testBit x 30 /= testBit x 31) = negate $ complementBit x 30
| otherwise = complementBit x 30

使用动态语言(Python)要容易得多。只需检查参数是否为数字 X 并返回一个返回 -X 的 lambda:

def f(x):
if isinstance(x,int):
return (lambda: -x)
else:
return x()

关于math - 设计函数 f(f(n)) == -n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/731832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com