Topic describes

This is LeetCode and this is LeetCode 7. Integer inversion, difficulty is simple.

Key words: number, reverse

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 [-231, 231-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: 321Copy the code

Example 2:

Input: x = -123 Output: -321Copy the code

Example 3:

Input: x = 120 Output: 21Copy the code

Example 4:

Input: x = 0 Output: 0Copy the code

Tip:

-231 <= x <= 231 – 1


To highlight

  1. The numbers are negative
  2. The inverted number has a size limit that cannot be exceededintRange of types

Their thinking

When we first invert an integer, we can get the last digit first, store it as the first digit, and then each time we fetch the preceding digit, the final digit is equal to the previous digit * 10 + the current digit.

class Solution {
    public int reverse(int x) {
        // Define the number after the inversion
        int ans = 0;
        int tmp;
        while(x ! =0) {
            // take the last digit
            tmp = x % 10;
            // Compute the inverted number
            ans = ans * 10 + tmp;
            // Remove the last bit of the integer
            x /= 10;
        }
        returnans; }}Copy the code

So we have the basic code, but we found that the inverted number might overflow, that is, go beyond the Integer.

So let’s go ahead and look at the code above to see what might be a problem, and we can locate ans = ANS * 10 + x % 10;

  1. For positive numbers: MAX_VALUE: ans > (integer.max_value – x % 10) / 10

  2. For negative numbers: ans * 10 + x % 10 < INTEger.min_value, ans < (integer.min_value -x % 10) / 10

The complete code is:

class Solution {
    public int reverse(int x) {
        int ans = 0;
        while(x ! =0) {
            if (x > 0 && ans > (Integer.MAX_VALUE - x % 10) / 10) {
                return 0;
            }
            if (x < 0 && ans < (Integer.MIN_VALUE - x % 10) / 10) {
                return 0;
            }
            ans = ans * 10 + x % 10;
            x /= 10;
        }
        returnans; }}Copy the code

reference

My Github repository has been set up synchronously, click access