'What method in Java returns the absolute difference of two integers?
Is there a method in the Java Math
class that returns the absolute difference of two integers?
int absDiff = 8 - 15;
int answer = 7;
Solution 1:[1]
There's no method in java.lang.Math
class that takes 2 int args and returns the absolute difference.
But you can simply do that using the following:
int a = 8;
int b = 15;
int absDiff = Math.abs(a - b);
Solution 2:[2]
You can use Math class abs method like below
int num1 = 8;
int num2 = 15;
int answer = Math.abs(num1 - num2);
And You can do this thing by logically also like below
int num1 = 8;
int num2 = 15;
int answer = (num1 - num2) * -1;
Solution 3:[3]
The previous answers all give the wrong result when the difference is above Integer.MAX_VALUE, for example when calculating the absolute difference between 2000000000 and -2000000000 (resulting in 294967296 instead of 4000000000). In that case the correct result cannot be represented by an int. The solution is to use long for the calculation and the result:
public static long absoluteDifference(int a, int b)
{
return Math.abs((long) a - b);
}
In some situations it's also okay to round down any difference greater than Integer.MAX_VALUE to Integer.MAX_VALUE (saturation arithmetics):
public static int absoluteDifferenceSaturated(int a, int b)
{
long absDiff = Math.abs((long) a - b);
return absDiff > Integer.MAX_VALUE ? Integer.MAX_VALUE : Math.toIntExact(absDiff);
}
For calculating the absolute difference of two longs, you may have to resort to BigInteger:
public static BigInteger absoluteDifference(long a, long b)
{
return BigInteger.valueOf(a).subtract(BigInteger.valueOf(b)).abs();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lavish Kothari |
Solution 2 | Batek'S |
Solution 3 | nmatt |