case1: x<0 , tmp=-x ,flag=1;
if (ans-1 > INT_MAX) return 0; OR return -ans
case2: x>=0, flag=0 ;
if(ans > INT_MAX) return 0;OR return ans
int reverse(int x) {
if( x == 0 )
return 0;
bool flag = 0;
long long ans = 0;
long long tmp = x;
if (x < 0)
{
//x = -x; Error!!! if x=-2147483648,it can't be represented by positive interger
//tmp = -x; ERROR!!! the same as former
tmp = -tmp;
flag = 1;
}
while( tmp )
{
ans = ans * 10 + tmp % 10;
tmp /= 10;
//must judge the border of ans at the end of this loop
if( (flag && ans-1 > INT_MAX ) || ans > INT_MAX )
return 0;
}
if( flag )
return -ans;
return ans;
}