Tuesday, February 3, 2015

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) {
        while (*str==' ')
            str++;
        bool negative = false;
        if (str[0]=='-')
        {
            negative = true;
            str++;
        }
        else if (str[0]=='+')
            str++;
        int res=0;
        while(*str!='\0')
        {
            if (*str>='0' && *str<='9')
            {
                if (!negative)
                {
                    if (res==INT_MAX/10 && *str>='7' || res>INT_MAX/10)
                        return INT_MAX;
                }
                else
                {
                    if (res==INT_MAX/10 && *str>='8' || res>INT_MAX/10)
                        return INT_MIN;
                }
                res = res*10 + *str-'0';
                str++;
            }
            else
            {
                break;
            }
        }
        if (negative)
            res = 0-res;
        return res;
    }
    
};

No comments:

Post a Comment