20

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 documentation but I'm bad at reading it and I can't find it. I know I've seen it somewhere though.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
David
  • 14,569
  • 34
  • 78
  • 107

6 Answers6

63

Integer.signum(int i)

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
Halo
  • 1,524
  • 3
  • 24
  • 39
6

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);
Neuron
  • 5,141
  • 5
  • 38
  • 59
Jack
  • 131,802
  • 30
  • 241
  • 343
1

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
Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
fortran
  • 74,053
  • 25
  • 135
  • 175
0

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:

  • 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.

Parameters:

  • d - the floating-point value whose signum is to be returned

Returns: The signum function of the argument

Since: 1.5

mgthomas99
  • 5,402
  • 3
  • 19
  • 21
zellio
  • 31,308
  • 1
  • 42
  • 61
0

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);

Chris Dennett
  • 22,412
  • 8
  • 58
  • 84
  • That should be `int ans` for both. – defectivehalt Mar 11 '10 at 17:34
  • 1
    Don't do this--it's going to make someone pause and think--that's the last thing you want in the middle of analyzing some bug. Make it an external method or break it out into an if (since the number is probably just input to an if statement anyway, it would be much clearer to simply say (if i<0) else if (i > 0) else... – Bill K Mar 11 '10 at 17:55
-1

For fun:

return (i > 0) ? 1 : ( (i < 0) ? -1 : 0 );
Tom Neyland
  • 6,860
  • 2
  • 36
  • 52