leetcode 之 String to Integer (atoi)

来源:互联网 发布:java种颜色代码 编辑:程序博客网 时间:2024/05/16 11:49

函数原型为:int atoi(const char *str)

注意特殊情况的处理:

1.指针为NULL的处理。

2.字符串头部有空格。

3.+和-号的处理。

4.整形溢出的处理,如INT_MAX (2147483647) 或 INT_MIN (-2147483648) 的处理。

5.特殊字符的处理,如  35cx等应当输出35等。

#include <assert.h>#include <limits.h>int atoi(const char *str){    assert(str!=NULL);           //whether  the pointer is null    const char * ptr=str;    while(*ptr==' ')             //ignore the space        ptr++;    bool positive=true;                 if((*ptr!='\0')&&*ptr=='+')       {        positive=true;        ptr++;    }    else if((*ptr!='\0')&&*ptr=='-')    {        positive=false;        ptr++;    }    int n=0;    while(*ptr!='\0')    {        if(*ptr>'9'||*ptr<'0')            break;        if (n > INT_MAX / 10 ||                 //if it is out of the range of representable values             (n == INT_MAX / 10 &&(*ptr - '0') > INT_MAX % 10))        {            return positive == false ? INT_MIN : INT_MAX;        }        if((*ptr<='9')&&(*ptr>='0'))        {            n=10*n+(*ptr-'0');            ptr++;        }    }    if(positive==false)        n=-1*n;    return n;}


0 0
原创粉丝点击