Reverse Integer
Example2: x = -123, return -321
_________________________________
注意溢出问题的处理;
int reverse(long long x) {
int flag = 0;
const long long max = 0x7fffffff; // long long 类型不管在32位还是在64位上,都是8个字节
const long long min = 0x80000000;
if (x < 0)
{
x = -x;
flag = -1;
}
long long sum = 0; //防止溢出
int a = 0;
while (x != 0)
{
sum = sum * 10;
a = x % 10;
sum = sum + a;
x = x / 10;
if (flag == 0 && sum > max)
{
return 0;
}
else if (flag == -1 && sum > abs(min))
{
return 0;
}
}
if (flag == -1)
sum = sum * (-1);
return sum;
}
notice:当 min 定义为 int 型时,abs()函数 对其是没有作用的,即:不能将其变为正数。