Is there any way to find the absolute value of a number without using the Math.abs() method in java.
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.