This was originally a very simple question, but there are too many restrictions and boundary conditions, and there will be many problems when making this question AC.
You only need to reverse the order of the numbers, but when the numbers are relatively large, (int)
the value range will overflow , so consider this boundary problem.
For example, if the number is too large, it overflows the int
value range and causes an error.
C language int
type ranges: [-2147483648,2147483647]
.
Multiply the number first and then judge, int
the value range will be exceeded .
Another way of thinking: first determine, and then multiply
. If the current number is greater than the int
maximum value divided by 10, then the number will definitely overflow.
If the current number is smaller than the int
minimum value divided by 10, then the number will definitely overflow.
Code:
int reverse(int x)
{
int rev = 0;
while (x != 0)
{
if (rev > INT_MAX / 10 || rev < INT_MIN / 10)
return 0;
rev = rev * 10 + x % 10;
x /= 10;
}
return rev;
}
INT_MAX
And INT_MIN
, are two macros. When debugging by yourself, limits.h
you can add the header file .