LeetCode 8. String to Integer (atoi) 字符串转整形

8. String to Integer (atoi)

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

1
2
Input: "42"
Output: 42

Example 2:

1
2
3
4
Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

Example 3:

1
2
3
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

1
2
3
4
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

1
2
3
4
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (−231) is returned.
直接转换

本题的关键的地方是要对一些边界情况和特殊的字符情况进行处理。由例子3我们可以知道,对于开头非0的字符串。我们需要对前两个字符进行处理

对于开头为空的字符串,我们可以先去掉空置,然后对剩余的字符串进行统一处理。

之后我们分为以下几种情况。

  1. 首先开头的字符串不为 ‘+’,‘-’和数字。那么直接返回的就是0

  2. 开头为 ‘+’或者 ‘-’。那么需要查看这个字符串的长度,如果长度仅仅为1的话,那么返回也依旧是0。如过长度是大于1的情况,就需要进一步判断第二个字符。

    1. 如果第二个字符为数字,那么就继续对剩余的数字进行判断。
    2. 如果第二个字符是非数字,那么也直接返回0.
  3. 在判断为前两个数字以后,剩余就继续判断剩余的字符。如果当中出现了非数字的字符,则直接返回目前的数字。

  4. 字符可以表示的数字范围会比整数要大,因此需要判断这个转换后的数字有没有溢出。如果出现上溢,则返回最大值的整数值。出现下溢,则返回最小的整数值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    public int myAtoi(String str) {
    double res = 0;
    str = str.trim();
    if(str == null || str.length() == 0){
    return 0;
    }
    int len = str.length();
    int i = 0;
    int sign = 1;
    if(len == 1){
    if(!isNumber(str.charAt(i))){
    return 0;
    } else {
    return str.charAt(i) - '0';
    }
    }


    if(str.charAt(i) == '-'){
    sign = -1;
    i++;
    }

    if( i == 0 &&str.charAt(i) == '+'){
    sign = 1;
    i++;
    }


    if(!isNumber(str.charAt(i))){
    return 0;
    }

    int max = Integer.MAX_VALUE/10;
    for(;i <= len -1 ;i++){
    if(isNumber(str.charAt(i))){
    res = res * 10 + (str.charAt(i) - '0');
    } else {
    break;
    }

    }

    if(res > Integer.MAX_VALUE){
    return sign == 1? Integer.MAX_VALUE:Integer.MIN_VALUE;
    }

    return (int)res*sign ;
    }

    public boolean isNumber(char str){
    return (str <= '9' && str >= '0');
    }
    使用符号位和进位

    和上述同理,只不过不将第一步和第二部单独拿出来进行处理。直接在循环当中进行处理。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    public int myAtoi(String str) {
    char[] value = str.toCharArray();
    double result = 0;
    int sign = 1;//表示正负号
    int index = 0;//第一个非空格的位置
    //遍历一遍,找出数字
    for(char c:value)
    {
    index++;
    if(c >= '0' && c <= '9'){
    result *= 10;
    result += (c - '0');
    }else if( c == '+' && index == 1){
    sign = 1;
    }else if (c == '-' && index == 1){
    sign = -1;
    }else if (c == ' ' && index == 1)
    {
    index--;
    }else {// 非数字符号空格的,直接返回 0
    break;
    }
    }
    //查看数字是否越界
    if(result > Integer.MAX_VALUE){
    if(sign == 1)
    return Integer.MAX_VALUE;
    else
    return Integer.MIN_VALUE;
    }else{
    return (int)(result * sign);
    }

文章作者: 彭峰
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 彭峰 !
 上一篇
2021-05-02 彭峰
下一篇 
2021-05-02 彭峰
  目录