首页 > 代码库 > LeetCode:String to Integer (atoi)

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

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


代码:

bool Solution::isNumber(char c)
{
    if(c >= '0' && c <= '9')
        return true;
    else
        return false;
}

int Solution::atoi(const char *str)
{
    int length = strlen(str);
    if(length == 0)
        return 0;
    char * temp = (char*)malloc(sizeof(char)*length);
    int temp_length = 0;
    char c;
    int start = 0;
    int positive = 1;
    long long result = 0L;
    for(int i = 0;i < length;i++)
    {
        c = str[i];
        if(start == 0 && c == ' ')
            continue;
        else if(start == 0 && (c == '+' || c == '-' || isNumber(c)))
        {
            start = 1;
            if(c == '-')
                positive = -1;
            if(isNumber(c))
            {
                temp[temp_length] = c;
                temp_length++;
            }
            continue;
        }
        else if(start == 0)
            return 0;
        else if(start == 1 && isNumber(c))
        {
            temp[temp_length] = c;
            temp_length++;
            continue;
        }
        else if(start == 1 && !isNumber(c))
            break;
    }
    long long x = 1L;
    for(int i = temp_length-1;i >= 0;i--)
    {
        result = result + (temp[i]-'0')*x;
        x = x * 10;
        if(result*positive > INT_MAX)
            return INT_MAX;

        if(result*positive < INT_MIN)
            return INT_MIN;
    }
    return result*positive;
}


LeetCode:String to Integer (atoi)