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

后端 未结 10 1553
轮回少年
轮回少年 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:11

    In case of the absolute value of an integer x without using Math.abs(), conditions or bit-wise operations, below could be a possible solution in Java.

    (int)(((long)x*x - 1)%(double)x + 1);
    

    Because Java treats a%b as a - a/b * b, the sign of the result will be same as "a" no matter what sign of "b" is; (x*x-1)%x will equal abs(x)-1; type casting of "long" is to prevent overflow and double allows dividing by zero.

    Again, x = Integer.MIN_VALUE will cause overflow due to subtracting 1.

提交回复
热议问题