LeetCode 8 :String to Integer (atoi)

问题是这样子的:

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.

平时写程序过于急躁,思考不深入,写这个看似容易的程序真是死了一大批脑细胞啊!!!反思,对于数值处理的问题,以及字符串处理的问题。

最重要的是:会不会溢出,会不会越界!!!

以下是我的代码,感觉略臭略长。如有大神帮改,感激不尽啊!!!

class Solution
{
public:
    int atoi(const char *str)
    {
        int ret = 0;
        const char *fStr = str;
        int signflag = 1;
        int signCount = 0;
        int intCount = 0;
        if(fStr == NULL )
        {
            return 0;
        }
        while(*fStr != '\0')
        {
            if(*fStr == 0x2D)
            {
                signflag = -1;
                ++signCount;
                fStr++;
            }
            if(*fStr == 0x2B)
            {
                signflag = 1;
                ++signCount;
                fStr++;
            }
            if(signCount > 1)
            {
                return 0;
            }
            if(isdigit(*fStr))
            {
                if(ret == INT_MAX/10 && *fStr >= 0x38 && signflag == 1)
                {
                    return INT_MAX;
                }
                else if(ret == INT_MAX/10 && *fStr > 0x38 && signflag == -1)
                {
                    return INT_MIN;
                }
                ret = 10 *ret + (*fStr-0x30);
                ++fStr;
                ++intCount;
                if(intCount > 10)
                {
                    return signflag >0 ? -INT_MIN-1 : INT_MIN;
                }
            }
            else if(*fStr ==' ')
            {
                if(intCount >= 1)
                {
                    return ret * signflag;
                }
                else if(signCount >= 1 && intCount ==0 )
                {
                    return 0;
                }
                fStr++;
            }
            else 
                return ret * signflag;

        }
        return ret * signflag;
    }

};

任重道远,爱情不光是甜蜜,更是一份责任。。。加油!!!

posted @ 2015-01-30 11:37  BestWangJie  阅读(135)  评论(0编辑  收藏  举报