7. Integer inversion

🌊

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≤x≤231−1][-2^{31} \leq x \leq 2^{31} -1][−231≤x≤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:


  • 2 31 Or less x Or less 2 31 1 -2^{31} \leq x \leq 2^{31} – 1

StringBuilder+ Exception handling mechanism 🔥

Ideas and Algorithms

The reverse() method provided by the StringBuilder class reverses a string, but it reverses an integer, so we need to convert the integer to a string and pass it into a parametered construct of the StringBuilder class;

A NumberFormatException is thrown when the value assigned to an int overflows. Since this is an exception, we do not do any extra processing after the exception is caught. It’s a good idea to just return 0.

Some numbers may be within the legal range, but reversing them would be out of range. Let’s say we have 2147483643, which is less than the largest 32-bit integer, 2147483647, but if we invert this number, we get 3463847412, which is larger than the largest 32-bit integer, and such a number cannot be stored in an int. So definitely return 0 (because of overflow).

code

class Solution {
    public static int reverse(int x) {
	// Determine whether x is positive or negative
        boolean flag = x < 0 ? true : false;
        
        StringBuilder reverse = new StringBuilder(Integer.toString(Math.abs(x))).reverse();
        try {
            Integer value = Integer.valueOf(reverse.toString());
            // Return the corresponding inverted integer based on the positivity or negativity of x
            return flag ? -value : value;
        } catch (NumberFormatException e) {
            // Do nothing
        }
        return 0; }}Copy the code

Submit the results

Mathematical methods 🔥

Ideas and Algorithms

First of all, how do you invert an integer? Using a stack? Or turn an integer into a string and then invert the string? These two ways are ok, but not good. In fact, we just need to get the “end number” of the whole number. Take 12345 as an example, first get 5, then get 4, then 3,2,1, we can splice a number in this order, also can achieve the “reverse” effect. How do I get the end number? Easy to do, with modular operation can be.

So it looks like we’ve done a loop, but we’re only dealing with positive numbers, and we’re dealing with negative numbers, so instead of x being greater than 0, we’re dealing with x! = 0. That way, the last division will make it zero, plus or minus, and for numbers like 12300, it will work perfectly!

It looks like that’s the end of the problem, but notice that it also says:

If the integer exceeds the range of 32-bit signed integers [−231≤x≤231−1][-2^{31} \leq x \leq 2^{31} -1][−231≤x≤231−1], 0 is returned.

Implicit: Some numbers may be in the legal range, but reversed out of range. For example, the number 2147483643 mentioned above. Such a reversal of the number cannot be stored in an int, so it must be determined in advance, rather than waiting for the last assignment to overflow. So, when we get to 1/10 of the largest number, the first digit of the end, we begin to judge:

If some number is greater than 2,14748,364, you don’t have to judge it anymore, it’s definitely overflowed.

If some number is less than -214748364, then you don’t have to judge it anymore, it definitely overflows.

But if a number is 214748364 or -214748364, it will not overflow, no need to judge… Take positive numbers: The last digit of the parameter must be greater than 7 to overflow, but this is determined after the inversion. Before the inversion, the number must start with >7 and the digit is equal to integer. MAX_VALUE. Same thing with negative numbers.

code

class Solution {
    public static int reverse(int x) {
        int remainder;
        int res = 0;
        while(x ! =0) {
            if ((res > Integer.MAX_VALUE / 10) || (res < Integer.MIN_VALUE / 10)) {
                return 0;
            }
            remainder = x % 10;
            res = res * 10 + remainder;
            x /= 10;
        }
        returnres; }}Copy the code

Submit the results

Type conversion 🔥

Ideas and Algorithms

Elegance never goes out of style!

The difficulty of this problem is to solve the overflow problem. Let’s think another way: why do we use int to receive in the first place? Why not just receive the number as a long and cast it to an int when it returns? This way, we don’t have to constantly evaluate if conditions in a while statement.

Data overflow may occur when casting from long to int, resulting in inconsistent data. Based on this principle to design the return statement, homeostatic complete the topic reverse integer overflow return 0 requirements.

code

class Solution {
    public static 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

Submit the results

📚 cheese

1. Char [], String, and Integer interconvert

Class Modifier and Type Method and Description
Integer static String toString(int i): Integer – String
Integer static Integer valueOf(String s): String – – Integer
String char[] toCharArray(): String — char[]
String static String valueOf(char[] data): char[] — String

2. Four ways to reverse a string:

Reference blog: blog.csdn.net/qq_43701760…

The last 🍺

This is No.2 in our “LeetCode” series, which began on 2021/08/31, with a total of 1949 titles in LeetCode as of the start date.

In this series of articles, in addition to explaining how to solve the problem, I will also present the most concise code possible.

See the [LeetCode] series for more details