# Solution in C++

• we can slove this problem like Hexadecimal conversion

MY CODE

``````class Solution {
public:
int reverse(int x) {
long long ans = 0;  //use long long for avoid overflow
while(x)
{
ans = ans * 10 + x % 10;
x /= 10;
}
if(x < 0) ans = ans * (-1);
return ans > INT_MAX || ans < INT_MIN ? 0 : ans;
}
};
``````

note :
because the answer maybe greater than 32-bit,so we should use long long insteat of int

A controversial code

``````class Solution {
public:
int reverse(int x) {
int dir = 1;
long long result = 0;
if(x < 0)
{
dir = -1;
x = -1 * x;
}
while(x)
{
result = result * 10 + (x % 10);
x = x / 10;
}
result = result * dir;
return (result < INT_MIN || result > INT_MAX) ? 0 : result;
}
};
``````

• This post is deleted!

• @DongChengrong When you do `x = -1 * x;` it will overflow for `x == INT_MIN` i.e. for `x == -2147483648` result for `x = -1 * x` will be still non-positive `-2147483648` due to overflow and later you will give wrong answer.

• @moytrage You are right,I will improve my algorithm.thanks you

• @moytrage said in Solution in C++:

@DongChengrong When you do `x = -1 * x;` it will overflow for `x == INT_MIN` i.e. for `x == -2147483648` result for `x = -1 * x` will be still non-positive `-2147483648` due to overflow and later you will give wrong answer.

How to solve it?

• @nijataa Don't worry! I use long long ,2 ^ 64,So if x = -1 * x will not overflow.But i think it isn't a good solution, so I will construct a better method to slove this problem

• This post is deleted!

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