class Solution {
public:
int reverse(int x) {
//only < 10
if(x/10 == 0) return x;
bool flag=true;
long xx=x;
if(x<0)
{
xx*=-1;
flag=false;
}
long ans =0 ;
while(xx != 0 )
{ if(ans*10+xx%10 > INT_MAX) return 0;
ans=ans*10+xx%10;
xx=xx/10;
}
if(!flag)
{
ans=ans*(-1);
}
return ans;
}
};
range int [-2^31 , 2^31 -1]
like reverse -2^31 --------> 2^31 ,that doesn’t work .
so we need to use long to store x
INT_MAX —>2^31 -1