I know such topic was asked several times, but my question is about overflow on full 32 bits of int. For example:
11111111111111111111111
The most intuitive method I can think of: calculate the sum (or difference) as a long
, then convert that sum to an int
and see if its value has changed.
long longSum = (long) a + b;
int sum = (int) longSum;
if (sum == longSum) {
// sum contains the correct result
} else {
// overflow/underflow
}
Remember that on modern 64 bit processors, working with long
s is no less efficient than working with int
s (the opposite may be true). So if you have a choice between checking for overflows or using long
s, go for the latter.