【leetcode边做边学】从atoi说起

atoi介绍

atoi即ASCII to integer,是把字符串转换成整型数的函数。
atoi看起来是一道很简单的题目,但是却考察了面试者写代码过程的各方面的能力————对于测试用例全面的考虑、良好编程的习惯、对代码漏洞和鲁棒性的保证。
对于技术面试而言,应聘者应该养成在写代码之前考虑所有可能的测试用例的习惯,保持思维逻辑的严谨。

atoi要求

Implement atoi to convert 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. If the correct value is out of the
    range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

第一版代码

C++代码

enum Status {kValid = 0, kInvalid};
int globalStatus = kValid;  

class StringHandling{
public:
    int atoi(const char *str){
        int number = 0;
        globalStatus = kInvalid;//value is not correct
        if (str != NULL)    //检测空指针
        {
            bool negative = false;
            if(*str != '\0')//检测空字符串
            {
                if(*str == '+')
                    str++;
                else if(*str == '-')
                {
                    negative = true;
                    str++;
                }
                while(*str != '\0')
                {
                    if (*str >= '0' && *str <= '9')
                    {
                        number = number*10 + (*str - '0');
                        str++;
                    }
                    else
                    {
                        number = 0;
                        break;
                    }
                }
                if(*str == '\0')
                {
                    globalStatus = kValid;//输入为有效
                    if (negative == true)//负数的情况
                    {
                        number = 0 - number;
                    }
                }
            }
        }
        return number;
    }
};

测试用例

  • 功能测试:输入的字符串表示正数、负数和0
  • 边界值测试:最大的正整数、最小的负整数
  • 特殊输入测试:输入字符串为NULL指针、输入字符串为空字符串、输入的字符串中又非数字字符
StringHandling sh;
cout << sh.atoi("") << "\t";
cout << "global status is: " << globalStatus << endl;
cout << sh.atoi(NULL) << "\t";
cout << "global status is: " << globalStatus << endl;
cout << sh.atoi("2368d") << "\t";
cout << "global status is: " << globalStatus << endl;
cout << sh.atoi("65433") << "\t";
cout << "global status is: " << globalStatus << endl;
cout << sh.atoi("-65433") << "\t";
cout << "global status is: " << globalStatus << endl;
cout << sh.atoi("--65433") << "\t";
cout << "global status is: " << globalStatus << endl;

显示结果

0       global status is: 1
0       global status is: 1
0       global status is: 1
65433   global status is: 0
-65433  global status is: 0
0       global status is: 1

存在的问题

  • 首先,这里定义了全局变量globalStatus来标记遇到非法输入的情况,虽然返回的整数是0,但当globalStatus为Invalid(Invalid=1)时,说明输入的字符串是非法操作。
  • 当输入时空字符串时,返回值是0,但globalStatus没有设置为Invalid
  • 当输入只有一个正号或者负号,后面没有跟数字,也不会设置globalStatus
  • 像最大正整数和最小负整数这样的边界条件没有考虑

参考代码

class Solution{
public:
    int atoi(const char *str)
    {
        long number = 0;
        globalStatus = kInvalid;
        if(str != NULL && *str != '\0')//检查NULL指针或者空字符
        {
            bool negative = false;
            if(*str == '+'){
                str++;
            }
            else if(*str == '-'){
                str++;
                negative = true;
            }
            if (*str != '\0')   //检查只有"+"或"-"的情况
            {
                number = StrToNumCore(str, negative);
            }
        }
        return (int)number;
    }
};

long StrToNumCore(const char *digit, bool negative)
{
    long num = 0;
    while(*digit != '\0')
    {
        if(*digit >= '0' && *digit <= '9')
        {
            int flag = negative ? -1 : 1;
            num = num*10 + flag*(*digit - '0');
            if((negative && num < (signed int)0x80000000) //检查最大正整数和最小负整数的边界
                || (!negative && num > 0x7fffffff))
            {
                num = 0;
                break;
            }
            digit ++;
        }
        else
        {
            num = 0;
            break;
        }
    }//while
    if(*digit == '\0')
    {
        globalStatus = kValid;
    }
    return num;
}

你可能感兴趣的:(【leetcode边做边学】从atoi说起)