Problem:String to Integer
这题看了一下,只有13%的AC,即使写出来也有各种各样的溢出问题,不知道oj是怎么写的,自己写的稍微复杂了一点,下面是在讨论区看见的简洁版。
int atoi(const char *str) {
int sign = 1, base = 0, i = 0;
while (str[i] == ' ') { i++; }
if (str[i] == '-' || str[i] == '+') {
sign = 1 - 2 * (str[i++] == '-');
}
while (str[i] >= '0' && str[i] <= '9') {
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
if (sign == 1) return INT_MAX;
else return INT_MIN;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}