设计函数 f(f(n)) == -n [英] Designing function f(f(n)) == -n

查看:11
本文介绍了设计函数 f(f(n)) == -n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A question I got on my last interview:

设计一个函数f,这样:

f(f(n)) == -n

其中 n 是一个 32 位 有符号整数;你不能使用复数算术.

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.

有什么想法吗?

推荐答案

怎么样:

f(n) = sign(n) - (-1)n * n

在 Python 中:

In Python:

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)

Python 自动将整数提升为任意长度的 long.在其他语言中,最大的正整数会溢出,因此它适用于除那个之外的所有整数.

Python automatically promotes integers to arbitrary length longs. In other languages the largest positive integer will overflow, so it will work for all integers except that one.

要使其适用于实数,您需要将 (-1)n 中的 n 替换为 { ceiling(n) if n>0;floor(n) 如果 n<0 }.

To make it work for real numbers you need to replace the n in (-1)n with { ceiling(n) if n>0; floor(n) if n<0 }.

在 C# 中(适用于任何双精度,溢出情况除外):

In C# (works for any double, except in overflow situations):

static double F(double n)
{
    if (n == 0) return 0;

    if (n < 0)
        return ((long)Math.Ceiling(n) % 2 == 0) ? (n + 1) : (-1 * (n - 1));
    else
        return ((long)Math.Floor(n) % 2 == 0) ? (n - 1) : (-1 * (n + 1));
}

这篇关于设计函数 f(f(n)) == -n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆