现在的位置: 首页 > 综合 > 正文

LeetCode–String to Integer

2018年10月01日 ⁄ 综合 ⁄ 共 545字 ⁄ 字号 评论关闭
int myAtoi(char *str) {
    if(str == NULL)
        return 0;
    while(*str == ' ' && *str != NULL)
        str++;
       
    if( *str == NULL )
        return 0;
    if( (*str > '9' || *str < '0') && (*str != '+' && *str != '-') )
        return 0;
        
    int digit = 1;
    if( *str == '+' || *str == '-')
    {
        digit = (*str=='+') ? 1 : -1;
        str++;
        if( *str == '+' || *str == '-')
            return 0;
    }
        
    long long sum = 0;
    while(*str != NULL)
    {
        if(*str >= '0' && *str <= '9')
        {
            sum = sum * 10 + *str - '0';
            if(sum > INT_MAX && digit == 1)
                return INT_MAX;
            if( (digit*sum) < INT_MIN && digit == -1)
                return INT_MIN;
        }
        else
            break;
        str++;
    }
    
    return sum*digit;
    
}

第一个在LeetCode主页做的题目,题目是简单的难度,但是写起来很崩溃,各种情况,幸好一一分析给化解了,但是题目确实有些地方表达不清楚,还得继续加油啊,不会用C++的string只好实用C。

抱歉!评论已关闭.