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) {
        if (str == NULL) return 0;
        
        int result = 0;
        while (*str == ' ') str++;
        
        int sign = 1;
        if (*str == '+') {
            str++;
        }
        else if (*str == '-') {
            sign = -1;
            str++;
        }
        
        while (*str >= '0' && *str <= '9') {
            if (result > INT_MAX / 10) {
                return sign == 1 ? INT_MAX : INT_MIN;
            }
            if (result == INT_MAX / 10) {
                if (sign == 1) {
                    return *str >= '7' ? INT_MAX : result * 10 + (*str - '0'); 
                }
                else {
                    return *str >= '8' ? INT_MIN : -result * 10 - (*str - '0');
                }
            }
            
            result = result * 10 + (*str - '0');
            str++;
        }
        
        return sign * result;        
    }
};

 

posted on 2014-12-28 17:50  风云逸  阅读(40)  评论(0)    收藏  举报