What Java method takes an int
and returns +1 or -1? The criteria for this is whether or not the int
is positive or negative. I looked through the docum
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:
NaN
, then the result is NaN
.Parameters:
Returns: The signum function of the argument
Since: 1.5
Integer.signum(int i)
Math.signum(value)
will do the trick but since it returns float or double (according to parameter) you will have to cast it:
int sign = (int)Math.signum(value);
or:
Integer.signum(value);
Strictly evaluating to -1 or 1, and cooler (probably more efficient too) than n < 0 ? -1: 1
:
(n >> 31) | 1
In case you want to use it for long
too:
(n >> 63) | 1
Use Integer.signum(int i)
, but if you want a custom in-line bit of code:
int ans = i < 0 ? -1 : 1;
if you want 0 also:
int ans = i == 0 ? 0 : (i < 0 ? -1 : 1);
For fun:
return (i > 0) ? 1 : ( (i < 0) ? -1 : 0 );