atoi 函数

  要考虑的情况蛮多,先自动忽略字符串前面的空白字符,然后接下来可以是数字或一个正负号,后面遇到非法字符就结束读取,

如果字符串是空串或者第一个就是非法字符就返回0,如果正溢出返回INT_MAX,负溢出返回INT_MIN

int myAtoi(char *str) {
    long long ans = 0;
    int pstr = 0,sign = 0;
    //去掉字符串前面的空格
    while(str[pstr] == ' ') pstr++;
    //判断正负号
    if(str[pstr] == '-') sign = 1;
    //如果第一个字符是正好或者负号,指针加一
    if(str[pstr] == '+' || str[pstr] == '-') pstr++;
    //保证无非法字符,以及溢出及时跳出
    while(str[pstr] >='0' && str[pstr]<='9' &&ans <INT_MAX){
        ans = ans*10 + (long long)(str[pstr] - '0');
        pstr++;
    }
    if(ans>INT_MAX) return sign ? INT_MIN:INT_MAX;
    return sign?-1*ans:ans;
}
原文地址:https://www.cnblogs.com/llei1573/p/4325765.html