- tags: C/C++
In some problems, we need to detect is our result overflow in a 32-bit integer. The key ideas is check our value before it becomes bigger.
For example:
// INT_MAX 2147483647
// INT_MIN -2147483648
// INT_MAX's suffix is 7
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && pop > 7)) {
return 0;
}
// INT_MIN's suffix is -8
if (res < INT_MIN / 10 || (res == INT_MIN / 10 && pop < -8)) {
return 0;
}
res = res * 10 + pop;
Our final result need a 10 times current value and plus a value, then we check:
- If our result greater than
INT_MAX / 10
, which means overflow. - Then if our result equals to
INT_MAX / 10
, we continue compare the plus value to the suffix of INT_MAX.