leetcode 之 String to Integer (atoi)

函数原型为: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值