String to Integer (atoi)

来源:互联网 发布:drgs病案编码软件 编辑:程序博客网 时间:2024/04/25 18:22

题目:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

例子:

input  "+1" output 1

input  "1a" output 1

input  "a1" output 0

input  "+23a1" output 23

input  "112  22" output 112

input  "   -   21" output 0

最大最小值:INT_MAX (2147483647) or INT_MIN (-2147483648)

代码如下:

int atoi(const char *str) {
        if(str==NULL)return 0;
        long long result=0;
        while(*str==' ')str++;
        bool flagsymbol=true,flagfirst=true,flagnum=true,flagflag=true;
        int n=0;
        while(*str!='\0')
        {
            if(*str=='-'||*str=='+')
            {
            n++;
            flagnum=false;
            if(n>1)return 0;
            if(*str=='-')flagsymbol=false;
            }
            else if(*str>='0'&&*str<='9')
            {
            if(flagnum||flagflag)
            result=result*10+(*str-'0'),flagnum=false;
            }
            else
            {
            if(flagfirst)return 0;
            flagflag=false;
            }
            str++;
            flagfirst=false;
        }
        if(flagsymbol)
        {
        if(result>INT_MAX )return INT_MAX ;
        return result;      
        }
        else
        {
        if(result>2147483648)return INT_MIN ;
        result*=-1;
        return result;
        }       
    }

原创粉丝点击