The key is how to detect integer overflow without store to a larger size integer.
For this purpose, we could detect integer overflow before carry:
-
The maximal of INT_MAX before carry is \(\frac{INT\_MAX}{10}\). We continue compare
pop
with the suffix of INT_MAX,7
, if maximal before carry is equal to \(\frac{INT\_MAX}{10}\). -
The minimal of INT_MIN before carry is \(\frac{INT\_MIN}{10}\) too. We continue compare
pop
with the suffix of INT_MIN,-8
, if minimal before carry is equal to \(\frac{INT\_MIN}{10}\).
class Solution {
public:
int reverse(int x) {
// INT_MAX 2147483647
// INT_MIN -2147483648
int res = 0, pop = 0;
while (abs(x) > 0) {
pop = x % 10;
x /= 10;
// 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;
}
return res;
}
};