# Share my C++ solution

• use long long int

``````class Solution {
public:
int reverse(int x) {
if (x == 0) return x;
int sign = 1;
long long int sum = 0;
if (x < 0)
x = -x, sign = -1;

while (x > 0)
{
sum = sum * 10 + (x % 10);
x /= 10;

if (sum * sign > INT_MAX || sum * sign < INT_MIN)
return 0;
}

return (int)sum * sign;
}
};
``````

without long long int

``````class Solution {
public:
int reverse(int x) {
if (x == 0) return x;
int sum = 0, low = 0, sign = 1;
if (x < 0)
x = -x, sign = -1;

while (x > 0)
{
low = x % 10;
if ((INT_MAX - low) / 10 < sum)
return 0;
sum = sum * 10 + low;
x /= 10;

}

return sign * sum;
}
};``````

• Is there some coincidence?
For the test case:-2147483648,statement "x = -x" is invalid(After execution,its value is also -2147483648).But for the value of sum is 0,the result is "return sign * 0".This test case is absolutely perfectly avoided.

• This is no coincidence,for x = -2147483648,the result of x = -x remains -2147483648,then it won't execution the loop,so it has no effect.

• You consider it very comprehensive,I also spend some time on thinking how to handle the overflow.

• I thought for a long time.I think perhaps your solution is the most concise.The best way to solve the overflow above is to avoid it.:-p

• "The best way to solve the overflow above is to avoid it",Fair enough.

• This post is deleted!

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