approach 1
pop and push digits & check before overflow
we can pop the last digit by using modulus operation.
before we push the digit to the answer, we should check if it could cause overflow.
C++ code 1
class Solution {
public:
int reverse(int x) {
int sign = x < 0? -1: 1;
if (sign < 0 && x == INT_MIN) return 0;
int res = 0;
x *= sign;
while (x) {
if (res > INT_MAX / 10 || res == INT_MAX / 10 && (x % 10) > (INT_MAX % 10))
return 0;
res = res * 10 + (x % 10);
x /= 10;
}
return sign * res;
}
};
C++ code 2
class Solution {
public:
int reverse(int x) {
int res = 0;
while (x){
int t = x % 10;
x /= 10;
if (res > 0 && res > (INT_MAX - t) / 10) return 0;
if (res < 0 && res < (INT_MIN - t) / 10) return 0;
res = res * 10 + t;
}
return res;
}
};