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

后端 未结 6 1176
無奈伤痛
無奈伤痛 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 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);

提交回复
热议问题