# Share my clean accepted C++ Solution without long type or magic number

• ``````class Solution {
public:
int reverse(int x) {
if (x == INT_MIN)
return 0;
if (x < 0)
return -reverse(-x);

int rx = 0; // store reversed integer
while (x != 0) {
// check overflow
if (rx > INT_MAX / 10 || 10 * rx > INT_MAX - x % 10) return 0;
rx = rx * 10 + x % 10;
x = x / 10;
}
return rx;
}
};``````

• Why rx > INT_MAX / 10 ? Not rx > INT_MAX..

• Because INT_MAX is the maximum integer type INT can represent. Since rx is also of type INT, it is not possible for rx to exceed INT_MAX. Essentially we are checking whether or not
rx = rx * 10 + x % 10
will result in overflow.

• This post is deleted!

• Would you please tell me that why it is rx > INTMAX / 10 || 10 * rx > INTMAX - x % 10 , not just 10 * rx > INT_MAX - x % 10 in the part of checking overflow?

• Because when you just use 10 * rx > INT_MAX - x % 10, if 10 * rx ,it will be overflow while rx become a new num < INTMAX.

• This post is deleted!

• Nice solution. We do not need the second part of the OR condition. Just ` rx > INT_MAX / 10 ` is sufficient to check for overflow.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.