class Solution { public: int atoi(const char *str) { int total; /* current total */ char sign; /* if '-', then negative, otherwise positive */ while ( isspace(*str) ) ++str; if (*str == '-' || *str == '+') sign = *str++; /* skip sign */ total = 0; while (isdigit(*str)) { if((INT_MAX-(*str-'0'))/10<total) { total=sign=='-'?INT_MIN:INT_MAX; } else total = 10 * total + (*str - '0'); /* accumulate digit */ str++; /* get next char */ } if (sign == '-') { total=-total; } return total; /* return result, negated if necessary */ } };
判断溢出还可以使用long long类型