Finding absolute value of a number without using Math.abs()

后端 未结 10 1557
轮回少年
轮回少年 2021-02-02 11:16

Is there any way to find the absolute value of a number without using the Math.abs() method in java.

10条回答
  •  逝去的感伤
    2021-02-02 12:16

    Yes:

    abs_number = (number < 0) ? -number : number;
    

    For integers, this works fine (except for Integer.MIN_VALUE, whose absolute value cannot be represented as an int).

    For floating-point numbers, things are more subtle. For example, this method -- and all other methods posted thus far -- won't handle the negative zero correctly.

    To avoid having to deal with such subtleties yourself, my advice would be to stick to Math.abs().

提交回复
热议问题