Skip to content

Instantly share code, notes, and snippets.

@serkan-ozal
Created August 23, 2014 08:48
Show Gist options
  • Save serkan-ozal/4b073a9ed6ecdacc2354 to your computer and use it in GitHub Desktop.
Save serkan-ozal/4b073a9ed6ecdacc2354 to your computer and use it in GitHub Desktop.
Integer comparison
/**
* Compares two integers by considering their signs.
*
* Suppose that
* i1 = -500.000.000
* i2 = 2.000.000.000
*
* Normally "i1 < i2", but if we use "i1 - i2" for comparison
* i1 - i2 = -500.000.000 - 2.000.000.000 and we may accept result as "-2.500.000.000".
* But the actual result is "1.794.967.296" because of overflow between
* positive and negative integer bounds.
*
* So, if we use "i1 - i2" for comparison, since result is greater than 0,
* "i1" is accepted as bigger that "i2". But in fact "i1" is smaller than "i2".
* Therefore, "i1 - i2" is not good way for comparison way between signed integers.
*
* @param i1 First number to compare with second one
* @param i2 Second number to compare with first one
* @return +1 if i1 > i2, -1 if i2 > i1, 0 if i1 and i2 are equals
*/
int compareIntegers(int i1, int i2) {
// i1 - i2 is not good way for comparison
if (i1 > i2) {
return +1;
} else if (i2 > i1) {
return -1;
} else {
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment