int reverse(int x)
{
int arr[20];
int n = x;
int result = 0;
int i = 0;
while (n != 0)
{
arr[i] = n % 10;
n = n / 10;
i++;
}
for (int j = 0; j < i; j++)
{
if (result > INT_MAX / 10 || result < INT_MIN / 10)
{
return 0;
}
result = arr[j] + result*10;
}
return result;
}
本代码是速度最快的,但内存较大。
本题的核心是如何判断反转之后的整数是否越界,也就是以上代码中的
if (result > INT_MAX / 10 || result < INT_MIN / 10)
如果越界,也只存在循环最后一次执行的相关判断