This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

The title

You are given a 32-bit signed integer x that returns the result of reversing the numeric portion of x.

If the inverted integer exceeds the range of 32-bit signed integers [−2^31, 2^31 − 1], 0 is returned.

Assume that the environment does not allow storage of 64-bit integers (signed or unsigned).

  • Example 1:

Input: x = 123 Output: 321

  • Example 2:

Input: x = -123 Output: -321

  • Example 3:

Input: x = 120 Output: 21

  • Example 4:

Input: x = 0 Output: 0

Tip:

-2^31 <= x <= 2^31 – 1

Answer:

  • The first thing to know about retrieving integers from the units digit to the first digit (from right -> left) are two operators
  1. Mod % : Mod a value that can get the units digit of an integer (x%10)
  2. Division / : Dividing by 10 shifts the units digit of an integer one to the left (x/10).
  • Prepare a box n and put the units digit taken out one by one into the box. When putting the units digit into the box, first shift the integers that may exist in the box to the left, leaving the last digit for the units digit (n*10), and then add the units digit (that is, the value of the integer remainder x%10).

Difficulty: overflow problem

Solution a:

If ignore the hypothesis, the first in the implementation process definition than a hypothesis (n type int) as a bigger box n type for long, is cast in return results for the data of long box type into the box type int, it don’t fit represents overflow, feedback 0, can put in shows no overflow, return to convert good type implementation

public int reverse(int x) { long n = 0; while(x ! = 0){ n = n*10 + x%10; x = x/10; } return (int)n==n? (int)n:0; }}Copy the code
Method 2:

According to the official correct solution, the overflow problem needs to be derived according to the formula: First, assume that the input value x is greater than 0, then divide by 10 (/10) and decompose by 10 (%10). The final result is that the box n above is less than or equal to (2^31-1)/10. Similarly, consider the case where x is less than 0, and the final box limit range is: 2^31/10 < n < (2^31-1)/10 implementation

    public int reverse(int x) {
        int n = 0;
        while (x != 0) {
            if (n < Integer.MIN_VALUE / 10 || n > Integer.MAX_VALUE / 10) {
                return 0;
            }
            n = n*10 + x%10;
            x /= 10;
        }
        return n;
    }
}

Copy the code