int atoi( const char *str ) { int answer = 0, symbol = 1, i = 0, n = 0; if( str == NULL ) { return 0; } for( i = 0; str[i] != '\0' && str[i] == ' '; ++i ) {} // 跳过前导空格. if( str[i] == '-' || str[i] == '+' ) { // 处理首个有效字符是符号位. symbol = str[i++] != '-' ? 1 : -1; } for( ; str[i] != '\0' && isdigit( str[i] ); ) { n = (str[i++] - '0') * symbol; if( (answer > INT_MAX / 10) || (answer == INT_MAX / 10 && n > INT_MAX % 10) ) { // 上溢出. return INT_MAX; } if( (answer < INT_MIN / 10) || (answer == INT_MIN / 10 && n < INT_MIN % 10) ) { // 下溢出. return INT_MIN; } answer = answer * 10 + n; } return answer; }