Leetcode8. String integer conversion

Title Description

Please come to implement a atoifunction, it can convert a string to an integer.

First, the function will begin with a space character discard useless if necessary, until the find to the first non-space character so far. The following conversion rules are as follows:

  • If the first character is a non-null positive or negative number, the sign of the back with as many consecutive numeric characters are combined to form a signed integer.
  • If the first non-space character is a number, which is directly after the continuous numeric characters are combined to form an integer.
  • The string may also exist after the integer part of the effective extra characters, these characters can be ignored, they should not affect the function.

Note : If the string when the first non-space character is not a valid integer character string is empty or contains only whitespace character string, the function does not require you to convert that conversion can not be effective.

In any case, if the function can not effectively convert, 0 is returned.

prompt:

  • The title of the whitespace characters, including space characters only ' '.
  • We assume that the environment can store 32-bit signed integer size, then the numerical range [-231 231--1]. If the value exceeds this range, return INT_MAX (231 - 1) or INT_MIN (-231).

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "-42"
Output: -42
Explanation: a first non-blank character '-', it is a negative sign.
  We will all digital consecutive negative number and later combined as much as possible, and finally get -42.

Example 3:

Input: "words and 987"
Output: 0
Explanation: a first non-blank character 'w', but it is not a positive number or negative number.
Therefore, the conversion can not be performed effectively.

Example 4:

Input: "-91283472332"
Output: -2147483648
explanation: the number "-91283472332" Over the range of 32-bit signed integer.
  So return INT_MIN (-231).

Description:

answer

I do not know Jiaosha, a law on Act II bar.

A method (java)

Ideas: step by step, in accordance with the subject of the request to remove the space, and then the symbol is determined, and finally the processing is digital. The most troublesome part of the boundary value that is determined, more intractable. May be referred to as big brother practice, the operation to one side, to ensure that in the case of not exceed the maximum, it is determined whether or not out of range.
Tip: The method of carrying as many as possible, as Character.isDigit (char c) to determine whether the numeric characters c. Str.trim or directly to the subject () to remove the character string String trailing spaces;


public class Solution {
    public int myAtoi(String str) {
        char[] chars = str.toCharArray();
        int n = chars.length;
        int idx = 0;
        while (idx < n && chars[idx] == ' ') {
            // 去掉前导空格
            idx++;
        }
        if (idx == n) {
            //去掉前导空格以后到了末尾了
            return 0;
        }
        boolean negative = false;
        if (chars[idx] == '-') {
            //遇到负号
            negative = true;
            idx++;
        } else if (chars[idx] == '+') {
            // 遇到正号
            idx++;
        } else if (!Character.isDigit(chars[idx])) {
            // 其他符号
            return 0;
        }
        int ans = 0;
        while (idx < n && Character.isDigit(chars[idx])) {
            int digit = chars[idx] - '0';
            if (ans > (Integer.MAX_VALUE - digit) / 10) {
                // 本来应该是 ans * 10 + digit > Integer.MAX_VALUE
                // 但是 *10 和 + digit 都有可能越界,所有都移动到右边去就可以了。
                return negative? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            ans = ans * 10 + digit;
            idx++;
        }
        return negative? -ans : ans;
    }
}

Complexity Analysis

  • time complexity: THE ( N ) O (N)
  • Space complexity: THE ( 1 ) O (1)

Method II (java)

Ideas: In fact, a similar idea, but this time will be a little faster, pay attention to whether num increase by 10 or are likely to be out of bounds, so we need to determine whether the two are out of bounds.


class Solution {
    public int myAtoi(String str) {
        //去掉str首尾的空格
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        char[] chars = str.toCharArray();
        int min = -2147483648;
        int max = 2147483647;
        int flag = 0;
        int sum = 0;
        
        if ((int) chars[0] == 45) {
            flag = 1;
        } else if ((int) chars[0] == 43) {
            flag = 0;
        } else if ((int) chars[0] < 48 || (int) chars[0] > 57) {
            return 0;
        } else {
            sum = (int) chars[0] - (int) ('0');
        }
        for (int i = 1; i < chars.length; i++) {
            if ((int) chars[i] < 48 || (int) chars[i] > 57) {
                break;
            }
            int num = (int) chars[i] - (int) ('0');
            if (flag == 0 && sum > max / 10) {
                return max;
            }
            if (flag == 1 && -sum < min / 10) {
                return min;
            }
            sum = sum * 10;
            if (flag == 0 && sum > max - num) {
                return max;
            }
            if (flag == 1 && -sum < min + num) {
                return min;
            }
            sum = sum + num;
        }
        if (flag == 1) {
            return -sum;
        }
        return sum;
    }
}

Complexity Analysis

  • time complexity: O ( N ) O (N)
  • Space complexity: O ( 1 ) O (1)

2020/4/3

Published 43 original articles · won praise 20 · views 1437

Guess you like

Origin blog.csdn.net/Chen_2018k/article/details/105304192