Just add this since no one wrote it here:
While you can use
Math.Abs(number1 - number2);
which is the easiest solution (and accepted answer), I am surprised that no one wrote what Abs actually does. Here's a solution that works in Java, C, C # and any other language with syntax like C:
int result = number1 - number2; if (result < 0) { result *= -1; }
It is so simple. You can also write it like this:
int result = number1 > number2 ? number1 - number2 : number2 - number1;
The latter can be even faster if it is compiled (both have the same subtraction, but in the former case there is a multiplication in some cases, and the latter is not). The first one actually does the work of Abs.
Mecki Dec 08 '08 at 11:11 2008-12-08 11:11
source share