【leetcode边做边学】从atoi说起

更多请关注我的HEXO博客:http://jasonding1354.github.io/

简书主页:http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles


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 << "test1\t";
cout << sh.atoi("") << "\t";
cout    << "global status is: " << globalStatus << endl;
cout << "test2\t";
cout << sh.atoi(NULL) << "\t";
cout    << "global status is: " << globalStatus << endl;
cout << "test3\t";
cout << sh.atoi("2368d") << "\t";
cout    << "global status is: " << globalStatus << endl;
cout << "test4\t";
cout << sh.atoi("65433") << "\t";
cout    << "global status is: " << globalStatus << endl;
cout << "test5\t";
cout << sh.atoi("-65433") << "\t";
cout    << "global status is: " << globalStatus << endl;
cout << "test6\t";
cout << sh.atoi("--65433") << "\t";
cout    << "global status is: " << globalStatus << endl;
cout << "test7\t";
cout << sh.atoi("--65433") << "\t";
cout    << "global status is: " << globalStatus << endl;
cout << "test8\t";
cout << sh.atoi("-") << "\t";
cout    << "global status is: " << globalStatus << endl;

显示结果

test1   0       global status is: 1
test2   0       global status is: 1
test3   0       global status is: 1
test4   65433   global status is: 0
test5   -65433  global status is: 0
test6   0       global status is: 1
test7   0       global status is: 1
test8   0       global status is: 0 <----false

存在的问题

  • 首先,这里定义了全局变量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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值