01 digital inversion.7

01 digital inversion.7

https://leetcode-cn.com/problems/reverse-integer/

Insert image description here

1. Comprehensive two ways of understanding

Understanding 1: Understand as reverse order output

Insert image description here

Understanding 2: Understand as head-to-tail exchange

Insert image description here

2. Choose data structure and algorithmic thinking choices

Option 1: Output in reverse order (violent solution)

  • Integer to string, string to array
  • Data structure: character array
  • Algorithmic Thinking: Traversal

Option 2: Head-to-tail swap (optimized solution)

  • Integer to string, string to array
  • Data structure: character array
  • Algorithmic Thinking: Traversal

Data structure - array

  • Array capacity is fixed
  • Use contiguous physical space to access data
  • O(1) complexity to read any element

3.Code basic solution and coding implementation

Solution 1: Violent solution

  1. Convert integer to string and then to character array
  2. Traverse the character array in reverse direction and store the elements in the new array
  3. Convert the new array to a string and then to an integer for output

Insert image description here

Solution 1: Violent solution to boundary and detail issues

  • Boundary issues:

    • Array index out of bounds

    • Numeric overflow boundary: if overflow returns 0

  • Details:

    • The first bit is not 0

    • Sign bit handling

Solution 1 I wrote: reverse order of char array

class Solution {
    
    
    public int reverse(int x) {
    
    
        int signed = x > 0 ? 1 : -1;
        long number = x;//这里转为long,避免溢出,
        number = Math.abs(number);
        //1. 整数转字符串,字符串转字符数组
        String str = String.valueOf(number);
        char[] oldCharArray = str.toCharArray();
        char[] newReveredCharArray = new char[oldCharArray.length];
        //2. 逆序输出字符数组
        for (int i = oldCharArray.length - 1; i >= 0; i--) {
    
    
            newReveredCharArray[oldCharArray.length - 1 - i] = oldCharArray[i];
        }
        //3. 字符数组转字符串,再转为整数
        String reversedStr = String.valueOf(newReveredCharArray);
        long unsignedResult = Long.parseLong(reversedStr);
        long result = signed * unsignedResult;
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
    
    
            result = 0;
        }
        return (int) result;
    }
}

Solution 2 I wrote: reverse API of StringBuffer in reverse order

    /**
     * 使用StringBuffer的reverse API简化数组操作
     */
    class Solution {
    
    
        public int reverse(int x) {
    
    
            int signed = x > 0 ? 1 : -1;
            long number = x;//这里转为long,避免Integer.MIN_VALUE取反溢出
            number = Math.abs(number);
            //1. 整数转字符串,字符串转字符数组
            String str = String.valueOf(number);
            //3. 字符数组转字符串,再转为整数
            String reversedStr = new StringBuffer(str).reverse().toString();
            long unsignedResult = Long.parseLong(reversedStr);
            long result = signed * unsignedResult;
            if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
    
    
                result = 0;
            }
            return (int) result;
        }
    }

Solution 3 I wrote: Another overflow judgment

class Solution {
    
    
    public int reverse(int x) {
    
    
        int signed = x > 0 ? 1 : -1;
        long number = x;//这里转为long
        number = Math.abs(number);
        //1. 整数转字符串,字符串转字符数组
        String str = String.valueOf(number);
        //3. 字符数组转字符串,再转为整数
        String reversedStr = new StringBuffer(str).reverse().toString();
        long unsignedResult = Long.parseLong(reversedStr);
        long result = signed * unsignedResult;
        if (result != (int) (result)) {
    
    //如果
            result = 0;
        }
        return (int) result;
    }
}

The solution given by Lagou.com: reverse order of char array

class Solution {
    
    
    /**
     * 编写代码时,先编写主体代码
     */
    public int reverse(int x) {
    
    
        if (x == Integer.MIN_VALUE) {
    
    
            // 整数类型最小值的绝对值 比 最大值的绝对值 大1
            return 0; // 反转必然溢出,返回0
        }
        int sign = x > 0 ? 1 : -1; // 符号
        x = x < 0 ? x * -1 : x; // 无论正负,都当成正数
        // 1.整数转字符串,再转字符数组
        String str = String.valueOf(x);
        char[] chars = str.toCharArray();
        // 2.反向遍历字符数组,并将元素存储到新数组中
        int len = chars.length;
        char[] array = new char[len];
        for (int i = 0; i < len; i++) {
    
     // 遍历新数组
            array[i] = chars[len - 1 - i];
        }
        // 3.将新数组转成字符串,再转成整数输出
        long value = Long.valueOf(String.valueOf(array));
        boolean b = value > Integer.MAX_VALUE || value < Integer.MIN_VALUE;
        int result = b ? 0 : (int) value; // 数值越界:溢出则返回0
        return result * sign; // 符号还原 }
    }
}

Time complexity and space complexity analysis

Time complexity: O(n)

  • Convert integer to string O(n)
  • Traversing character array O(n)
  • O(n) +O(n)=O(2n)
  • After ignoring constants: O(n)

Space complexity: O(n)

  • A string O(n)
  • A new array O(n)
  • O(n) +O(n)=O(2n)
  • After ignoring constants: O(n)

Solution 2: Swap head and tail

  1. Convert integer to string and then to character array
  2. Traverse the character array and swap the elements in the array head to tail.
  3. Convert the new array to a string and then to an integer for output

Solution 2: Swap boundaries and details from head to tail

  • border issues
    • Array index out of bounds
      • The array is an even number and the completion flag is start>end
      • The array is an odd number and the completion flag is start=end
      • So the boundary condition is start<end
    • Numeric overflow boundary: if overflow returns 0
  • Details
    • The beginning and the end are not 0
    • symbol processing

Solution 1 I wrote: Swap the head and tail of the char array

class Solution {
    
    
    public int reverse(int x) {
    
    
        int signed = x > 0 ? 1 : -1;
        long number = x;//这里转为long
        number = Math.abs(number);
        //1. 整数转字符串,字符串转字符数组
        String str = String.valueOf(number);
        char[] charArray = str.toCharArray();
        //2. 逆序输出字符数组
        int startIndex = 0, endIndex = charArray.length - 1;
        while (startIndex < endIndex) {
    
    
            char temp = charArray[startIndex];
            charArray[startIndex] = charArray[endIndex];
            charArray[endIndex] = temp;
            startIndex++;
            endIndex--;
        }
        //3. 字符数组转字符串,再转为整数
        String reversedStr = String.valueOf(charArray);
        long unsignedResult = Long.parseLong(reversedStr);
        long result = signed * unsignedResult;
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
    
    
            result = 0;
        }
        return (int) result;
    }
}

The solution given by Lagou.com: Swap the beginning and end of the char array in place

class Solution {
    
    
    /**
     * 编写代码时,先编写主体代码
     */
    public int reverse(int x) {
    
    
        if (x == Integer.MIN_VALUE) {
    
    
            // 整数类型最小值的绝对值 比 最大值的绝对值 大1
            return 0; // 反转必然溢出,返回0
        }
        int sign = x > 0 ? 1 : -1; // 符号
        x = x < 0 ? x * -1 : x; // 无论正负,都当成正数
        // 1.整数转字符串,再转字符数组
        String str = String.valueOf(x);
        char[] chars = str.toCharArray();
       int startIndex = 0, endIndex = chars.length - 1;
        while (startIndex < endIndex) {
    
    
            char temp = charArray[startIndex];
            chars[startIndex] = chars[endIndex];
            chars[endIndex] = temp;
            startIndex++;
            endIndex--;
        }
        // 3.将新数组转成字符串,再转成整数输出
        long value = Long.valueOf(String.valueOf(chars));
        boolean b = value > Integer.MAX_VALUE || value < Integer.MIN_VALUE;
        int result = b ? 0 : (int) value; // 数值越界:溢出则返回0
        return result * sign; // 符号还原 }
    }
}

Time complexity and space complexity

Time complexity: O(n)

  • Convert integer to string O(n)

  • Traversing character array O(n)

  • O(n) +O(n)=O(2n)

  • After ignoring constants: O(n)

Space complexity: O(n)

  • A string O(n)
  • A new array O(n)
  • Absolute space consumption reduction: O(n)

4.Consider thinking about better solutions and coding implementation

  1. Eliminate invalid code or optimize space consumption
  • Is the operation necessary?
  • Are data structures necessary?
  1. In search of better algorithmic thinking
    • Since it is an integer, can we think mathematically?
    • Learn from other algorithms

Solution: mathematical thinking solution

Insert image description here

Mathematical thinking to solve boundary and detail problems

  • border issues

    • When will it end?

    • Processed from low bit to high bit, ending with the highest bit

      1. Highest bit/10==0
      2. Highest bit %10==Highest bit
    • Numeric overflow boundary: if overflow returns 0

      • Use long to store it, and return 0 if it overflows int.
      • Overflow is judged before the new integer is supplemented with the last digit.
  • Details

    • Same as above

5. Code optimal solution ideas and coding implementation

Solution 1 I wrote: Mathematical thinking method

class Solution {
    
    
    public int reverse(int x) {
    
    
        if (x == Integer.MIN_VALUE) {
    
    
            //因为Integer.MIN_VALUE的绝对值必溢出,Integer.MAX_VALUE的绝对值不会溢出
            return 0;
        }
        int signed = x > 0 ? 1 : -1;
        long number = Math.abs(x);
        long digit;
        long unSignedResult = 0;
        while (number != 0) {
    
    
            digit = number % 10;
            unSignedResult = unSignedResult * 10 + digit;
            number = number / 10;
        }
        long result = unSignedResult * signed;
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
    
    
            result = 0;
        }
        return (int) result;
    }
}

Time complexity and space complexity

Time complexity: O(n)

• Iterate over each bit of an integer: O(n)

Space complexity: O(1)

• Only one integer variable is required O(1)

6.Change deformation extension

  • (Exercise) Reverse long integer data
  • (Exercise) Reverse a string

7. Optimal solution universal solution

class Solution {
    
    
    public long reverse(long x) {
    
    
        long result = 0;
        while (x != 0) {
    
    
            if (result > Long.MAX_VALUE / 10 || result < Long.MIN_VALUE / 10) {
    
    
                return 0;
            }
            long digit = x % 10;
            x /= 10;
            result = result * 10 + digit;
        }
        return result;
    }
}

Insert image description here

Guess you like

Origin blog.csdn.net/sinat_26394043/article/details/132678200
01