(C language version) Given a 32-bit signed integer, you need to reverse the digits on each of the integers.

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.
Insert picture description here
For example, if the number is too large, it overflows the intvalue range and causes an error.
C language inttype ranges: [-2147483648,2147483647].

Multiply the number first and then judge, intthe value range will be exceeded .

Another way of thinking: first determine, and then multiply
. If the current number is greater than the intmaximum value divided by 10, then the number will definitely overflow.
If the current number is smaller than the intminimum 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_MAXAnd INT_MIN, are two macros. When debugging by yourself, limits.hyou can add the header file .

Guess you like

Origin blog.csdn.net/w903414/article/details/108300600