LeetCode No.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.

这题又是一道vaguely到吐血的题。我要过OJ我不看你的Spoiler如何才能处理啊!

不过确实,一Run才知道有很多情况都没想到。我当初的想法是,我只处理合法数字串。开头的空格没想到,中间夹杂其他字符确实想到了,但我的处理方法是直接返回0。

另外还有溢出问题。一提整数,就要想到可能溢出。以后要锻炼这种思维。用Python写的就感谢Guido吧。

代码如下:

int atoi(const char *str) {
        int i = 0, len = strlen(str), res = 0, t, sign = 1;

        while (isspace(str[i]))
            i++;

        if (str[i] == '+' || str[i] == '-') {
            if (str[i] == '-') sign = -1;
            i++;
        }

        if (strcmp(str, "2147483647") == 0)
            return 2147483647;

        if (strcmp(str, "-2147483648") == 0)
            return -2147483648;

        for (; i < len; i++) {
            if (str[i] >= '0' && str[i] <= '9') {
                t = res * 10 + str[i] - '0';
                if ((t - str[i] + '0') / 10 != res || t < res) {
                    return sign == 1 ? INT_MAX : INT_MIN;
                }
                else {
                    res = t;
                }
            }
            else {
                return res * sign;
            }
        }
        return res * sign;
    }

 

posted @ 2015-01-14 16:56  _Anonyme  阅读(111)  评论(0编辑  收藏  举报