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.

注意事项

  • 去掉前面的空白
  • 处理正负号
  • 遇到非数字量结束转换 如 111aaa 返回 111
  • 非正常数字返回 0 如 aa11
  • 溢出返回最大/最小值
int myAtoi(string str) {
    long long result = 0;
    int sign = 1;
    int i = 0;
    //处理空白
    for(; i < str.size(); ++i){
        if(str[i] != ' ') break;
    }
    //处理符号
    if(str[i] == '+' || str[i] == '-'){
        sign = (str[i++] == '+' ? 1 : -1);
    }
    //计算数值
    for(; i < str.size(); ++i){
        if(str[i] >= '0' && str[i] <= '9')
            result = result * 10 + (str[i] - '0');
        //非数字退出返回
        else 
            break;
        //溢出处理
        if(result > INT_MAX) 
            return sign == 1 ? INT_MAX : INT_MIN;
    }
    
    return result * sign;
}

另一种写法

int myAtoi(string str) {
    int ret = 0, sign = 1, i = str.find_first_not_of(' '), base = INT_MAX / 10;
    if (str[i] == '+' || str[i] == '-') sign = str[i++] == '+' ?: -1;
    while (isdigit(str[i])) {
        if (ret > base || (ret == base && str[i] - '0' > 7)) 
            return sign > 0 ? INT_MAX : INT_MIN;
        ret = 10 * ret + (str[i++] - '0');
    }
    return sign * ret;
}

你可能感兴趣的:(8. String to Integer (atoi))