5

两个和函数构造相关的趣味面试题

 2 years ago
source link: https://blog.yxwang.me/2009/06/two-function-related-interview-questions/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

两个和函数构造相关的趣味面试题

Mon, Jun 1, 2009 • Algorithms

http://stackoverflow.com/questions/731832/interview-question-ffn-n

http://stackoverflow.com/questions/732485/interview-question-ffx-1-x

问题描述很简单,第一个问题是实现一个函数f,参数为一个带符号的32位整型,使得f(f(x)) = -x,即调用两次后返回的结果为原来的相反数;另一个问题也是实现一个函数g,参数为一个32位浮点,最后使得g(g(x)) = 1/x。如果不能满足所有的情况,就满足尽可能多的情形。

第二个问题比第一个问题简单一点,目前支持数最高的两个答案如下:

问题1的解无法满足n = 2^31 - 1的情况

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)

问题2的解的想法也很巧妙

float f(float x)
{
    return x >= 0 ? -1.0/x : -x;
}
本作品采用知识共享署名-非商业性使用 3.0 版本许可协议进行许可,欢迎转载,演绎,但是必须保留本文的署名 zellux(包含链接),且不得用于商业目的。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK