LeetCode: String to Integer (atoi)

思路:很多边界情况需要加以处理,主要部分不是很难,详见代码。

code:

class Solution {
public:
    int atoi(const char *str) {
        const char * p = str;
        while(*p == ' ')
            p++;
        int flag = 1;
        if(*p == '-'){
            flag = -1;
            p++;
        }
        else if(*p == '+')
            p++;
        long long ret = 0;
        while(*p != '\0'){
            if(*p > '9' || *p < '0')break;
            ret *= 10;
            int temp = *p - '0';
            ret += temp;
            p++;
        }
        ret *= flag;
        if(ret > INT_MAX) return INT_MAX;
        if(ret < INT_MIN) return INT_MIN;
        return ret;
    }
};


你可能感兴趣的:(LeetCode: String to Integer (atoi))