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.
Asked
Active
Viewed 1.8k times
20

C. K. Young
- 219,335
- 46
- 382
- 435

David
- 14,569
- 34
- 78
- 107
-
What about 0, is it positive or negative? – fortran Mar 11 '10 at 17:25
-
@fortran: The prevailing `signum` answer takes care of that too. – C. K. Young Mar 11 '10 at 17:27
-
@Chris and @Halo that's the point, the op wants +1 or -1 on any int, not zero... – fortran Mar 11 '10 at 17:32
-
+1 because I had no idea this method existed, though I'm not sure when I would ever use it... – Pops Mar 11 '10 at 17:33
-
3you do realize that in the time it took you to read the doc, post this question, and wait for the answer, you could have written a function to do exactly what you needed and gone to lunch? – Steven A. Lowe Mar 11 '10 at 17:41
-
@steven. that's a good point. I might need it again in the future though in whcih case this will be faster overall. – David Mar 11 '10 at 17:47
-
@David: only if you remember the name of the function later ;-) – Steven A. Lowe Mar 11 '10 at 20:38
6 Answers
63
-
-
1thanks. i don't supsoe theres a version that will return 1 when 0 is entered? or do i have to create that myself? – David Mar 11 '10 at 18:06
-
someone below gave an implementation, I suppose it's true.. you can modify it your way – Halo Mar 11 '10 at 18:09
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 isNaN
. - 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
-
-
1Don'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