Skip to content

Latest commit

 

History

History
38 lines (37 loc) · 904 Bytes

8.md

File metadata and controls

38 lines (37 loc) · 904 Bytes

#8. String to Integer (atoi) 题目链接

// 有太多的边缘条件,感觉不是一道很好的题目
int myAtoi(char* str) {
    int pn = 0;
    int flag = 0;
    int i = 0;
    int number = 0;
    while(str[i]=='+'||str[i] == '-'||str[i]  == ' ')
    {
        if((str[i+1]=='+'||str[i+1]=='-'||str[i+1]  == ' ')&&(str[i]=='+'||str[i] == '-'))
            return 0;
        i++;
    }
    pn = i - 1;
    for(i; str[i]!=0; i++)
    {
        if((flag= str[i]-'0')>=10||flag<0)
            break;
        if(number*10> INT_MAX - flag||number>INT_MAX/10)
        {
            if(str[pn] == '-' )
            {
                return -2147483648;
            }
            return 2147483647;
        }
        number = number*10 + flag;
        
    }
    if(str[pn] == '-' )
    {
        number = -number;
    }
    return number;
}