什么 Java 方法接受一个 int 并返回 +1 或 -1?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2427159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:05:39  来源:igfitidea点击:

What Java method takes an int and returns +1 or -1?

java

提问by David

What Java method takes an intand returns +1 or -1? The criteria for this is whether or not the intis positive or negative. I looked through the documentation but I'm bad at reading it and I can't find it. I know I've seen it somewhere though.

什么 Java 方法接受 anint并返回 +1 或 -1?对此的标准是它int是正的还是负的。我浏览了文档,但我不擅长阅读,也找不到。我知道我在某处见过它。

回答by Hyman

Math.signum(value)will do the trick but since it returns float or double (according to parameter) you will have to cast it:

Math.signum(value)会做的伎俩,但由于它返回 float 或 double (根据参数),你将不得不投它:

int sign = (int)Math.signum(value);

or:

或者:

Integer.signum(value);

回答by fortran

Strictly evaluating to -1 or 1, and cooler (probably more efficient too) than n < 0 ? -1: 1:

严格评估为 -1 或 1,并且比以下更酷(也可能更有效)n < 0 ? -1: 1

(n >> 31) | 1

In case you want to use it for longtoo:

如果您也想将其用于long

(n >> 63) | 1

回答by Chris Dennett

Use Integer.signum(int i), but if you want a custom in-line bit of code:

使用Integer.signum(int i),但如果您想要自定义的内嵌代码:

int ans = i < 0 ? -1 : 1;

int ans = i < 0 ? -1 : 1;

if you want 0 also:

如果你也想要 0:

int ans = i == 0 ? 0 : (i < 0 ? -1 : 1);

int ans = i == 0 ? 0 : (i < 0 ? -1 : 1);

回答by zellio

Math.signum(double i)

Math.signum(double i)

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero. Special Cases:

返回参数的符号函数;如果参数为零,则为零,如果参数大于零,则为 1.0,如果参数小于零,则为 -1.0。特别案例:

  • If the argument is NaN, then the result is NaN.
  • If the argument is positive zero or negative zero, then the result is the same as the argument.
  • 如果参数为NaN,则结果为NaN
  • 如果参数为正零或负零,则结果与参数相同。

Parameters:

参数:

  • d - the floating-point value whose signum is to be returned
  • d - 要返回其符号的浮点值

Returns: The signum function of the argument

返回: 参数的符号函数

Since: 1.5

自:1.5

回答by Tom Neyland

For fun:

为了娱乐:

return (i > 0) ? 1 : ( (i < 0) ? -1 : 0 );