Leetcode——String to Integer (atoi)

题目描述

Implement atoi which converts a string to an integer.

实现atoi,将字符串转成对应的整型

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:

仅仅只有空格才被认为是空白字符
假设我们的环境仅仅能够存储32位的整型数据,范围是[−231, 231 − 1]。如果数字的值超过了这个范围,那么就返回INT_MAX (231 − 1) 和INT_MIN (−231)


Input: “42”
Output: 42
Example 2:


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:


Input: “4193 with words”
Output: 4193
Explanation: Conversion stops at digit ‘3’ as the next character is not a numerical digit.
Example 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:


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.

思路分析

  • 照我的理解就是扫描字符串,获取特定范围的整型数组。

我的代码

int myAtoi(char *str)
{
    int flag = 0,res = 0,num = 0;
    //  去除空格
    while(*str== ' ')
    {
        str ++;
    }
    //获取正负号,并判定去除所有空格之后的第一位
    switch (*str)
        {
            case '-':
                flag = 0;
                break;
            case '+':
                flag = 1;
                break;
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
                flag = 1;
                res = res + *str - 48;
                break;
            default:
                return 0;
        }
    str ++;
    while(*str)
    {
        //不是数字或者正负号直接退出
        switch (*str)
        {
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
                num = *str - 48;

                if(res > 214748364
                    || (res == 214748364 && num > 7))
                {
                    return 2147483647;

                }
                if(res < -214748364
                   || (res == -214748364 && num > 8))
                {
                    return -2147483648;
                }
                if(flag == 0)
                {
                    res = 10 * res - num;
                }
                else
                {
                    res = res * 10 + num;
                }
                break;
            default:
                return res;
        }
        str ++;
    }
    return res;
}

分析与总结

  • 在整形条件下判定数是否发生越界

Leetcode——String to Integer (atoi)_第1张图片

   if(res > 214748364
                    || (res == 214748364 && num > 7))
   {
         return 2147483647;
   }
   if(res < -214748364
                   || (res == -214748364 && num > 8))
   {
         return -2147483648;
   }
 *  如果记不住上述的边界的数字,可以用十六进制进行计算
 *  将字符转成对应的ASCII码,我用的方法结果都是正数,每一位都是十以内的正数,没有负数,所以注意修改边界
  • 同时关于判定需要注意的是:先去判定大小,再去使用迭代式sum = sum * 10 + num,方式发生越界。
  • char型直接和整型参与运算,会自动转成ASCII码,0 ~ 9对应的ASCII码是48 ~ 57,转成整型的数字记得减去48
  • 正数和负数的叠加和生成方法
if(flag == 0)
{
     res = 10 * res - num;
}
else
{
      res = res * 10 + num;
 }
  • 字符串的结束符 ‘\0’,是bool型,判定是0,非‘\0’判定是非零,为真。用来滤除空格
 while(*str== ' ')
    {
        str ++;
    }
  • 同时判定多个条件某一个是否发生,用switch,别傻傻的用一个if,然后中间用多个‘||’,连接起来
switch (*str)
        {
            case '-':
                flag = 0;
                break;
            case '+':
                flag = 1;
                break;
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
                flag = 1;
                res = res + *str - 48;
                break;
            default:
                return 0;
        }

不是这个,一个if最多链接两个条件

if(.. || ...||...||...||)
{
}

完善和修改

int myAtoi(char *str)
{
    int flag = 1,res = 0,num = 0;
    //  去除空格
    while(*str== ' ')
    {
        str ++;
    }
	//判定符号
    if(*str == '-')
    {
        flag = 0;
        str ++;
    }
    else if(*str == '+')
    {
        str ++;
    }
	//读取数字
    while(*str)
    {
        //不是数字或者正负号直接退出
        switch (*str)
        {
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
                num = *str - 48;
                if(res > 214748364
                    || (res == 214748364 && num > 7))
                {
                    return 2147483647;

                }
                if(res < -214748364
                   || (res == -214748364 && num > 8))
                {
                    return -2147483648;
                }
                if(flag == 0)
                {
                    res = 10 * res - num;
                }
                else
                {
                    res = res * 10 + num;
                }
                break;
            case '+':
            case '-':
            default:
                return res;
        }
        str ++;
    }
    return res;
}
  • flag两种值,但是仅仅在识别到负号的情况下才改变,识别正号就不发生改变。所以标签值改变少数,不改变多数
  • switch-case语句可以较好的判定的一个字符是否属于特定的范围。

C中自带的atoi函数的介绍

  • 用法:将字符串离的数字字符转化为整型数,返回整型数值
  • 注意:转化时,自动跳过前面的空格字符,直到遇上数字或者正负符号才开始做转换,在遇到非数字或者字符结束标志,将结果返回。

你可能感兴趣的:(leetcode)