48. Reverse numbers
Title description
Flip the given 32-bit integer x.
Example 1: x=123, return 321
Example 2: x=-123, return -321
Have you noticed that the integer after flipping may overflow? Because the given is a 32-bit integer, its value range is −2^{31}, 2^{31} − 1. Flip may cause overflow, if the result after inversion will overflow, return 0.
enter
-123
return value
-321
analysis
1. To reverse the numbers, you first need to get the number of each digit, and then you can reverse
2. Then get the last digit first, and take the remainder of the entered digits to get the last digit
3. Then add it to the new result, because it is an inversion, so multiply the original by 10 and add the newly obtained number
4. Determine whether it overflows, if the new value minus the just obtained divided by 10 is not equal to res, it means overflow
Code
public static int reverse(int x) {
int res = 0;
while (x != 0) {
int tail = x % 10;
int newRes = res * 10 + tail;
if ((newRes - tail) / 10 != res) {
return 0;
}
res = newRes;
x = x / 10;
}
return res;
}