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

后端 未结 6 1140
無奈伤痛
無奈伤痛 2021-02-18 17:03

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

相关标签:
6条回答
  • 2021-02-18 17:48

    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

    0 讨论(0)
  • 2021-02-18 17:52

    Integer.signum(int i)

    0 讨论(0)
  • 2021-02-18 18:04

    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);
    
    0 讨论(0)
  • 2021-02-18 18:07

    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
    
    0 讨论(0)
  • 2021-02-18 18:07

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

    0 讨论(0)
  • 2021-02-18 18:07

    For fun:

    return (i > 0) ? 1 : ( (i < 0) ? -1 : 0 );
    
    0 讨论(0)
提交回复
热议问题