I need to check if two integers are on the same side of zero many times. I don\'t care if it\'s positive or negative, just that it\'s the same side... and performance is very im
if (int1 == 0 || int2 == 0) {
// handle zero
} else if ((int1 >> 31) == (int2 >> 31)) {
// same side
} else {
// different side
}
or
if (int1 == 0 || int2 == 0) {
// handle zero
} else if ((int1 & Integer.MIN_VALUE) == (int2 & Integer.MIN_VALUE)) {
// same side
} else {
// different side
}
The idea of both is the same - strip all but the sign bit, and then compare that for equality. I'm not sure which is faster, the right shift (>>) or the bitwise and (&).