剑指offer——把字符串转换成整数

字符串转成整数的核心代码很简单,但是需要考虑的各种情况很多。

1、首位+、-的判断。

2、在+、-的溢出判断。

3、NULL、空字符串的判断。

4、数字后面出现了很多非数字的情况。atoi函数是讲前面的数字保存下来,《剑指offer》的代码则是返回0。两种情况都说的通,视情况而定吧。

5、开头出现了很多非数字,中间掺杂着数字的出现,直接返回0。

#include <iostream>
using namespace std;

enum{
    kValid=0,
    kInvalid
};

int status=kValid;

long StrToIntCore(const char* digit, bool minus)
{
    long num=0;
    while(*digit!='')
    {
        if (*digit>='0'&&*digit<='9')
        {
            int flag=minus?-1:1;
            num=num*10+flag*(*digit-'0');
            if (!minus&&num>0x7FFFFFFF||minus&&num<(signed int)0x80000000)
            {
                num=0;
                break;
            }
            digit++;
        }
        else
        {
            break;
        }
    }
    if (*digit=='')
    {
        status=kValid;
    }
    return num;
}

int StrToInt(const char* str)
{
    status=kInvalid;
    long num=0;
    if (str!=NULL&&*str!='')
    {
        bool minus=false;
        if (*str=='+')
        {
            str++;
        }
        else if(*str=='-')
        {
            str++;
            minus=true;
        }
        if (*str!='')
        {
            num=StrToIntCore(str,minus);
        }
    }
    return num;
}

int main()
{
    char str[100];
    while(cin>>str){
        cout<<StrToInt(str)<<endl;
        cout<<atoi(str)<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dgy5554/p/3973392.html