最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

SEO心得admin31浏览0评论
本文介绍了设计函数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自动将整数提升为任意长度的长度。在其他语言中,最大的正整数将溢出,因此它将适用于除了那个之外的所有整数。

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.

使其成为可能如果n> 0,则需要用 {ceiling(n)替换(-1) n 中的 n 。 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#中(适用于任何double,除了溢出情况):

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)); }
发布评论

评论列表(0)

  1. 暂无评论