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.
C Solution 1:
int myAtoi(char* str) {
for (; *str == ' ';str++);
int sign = 1;
if (*str == '-' || *str == '+') {
sign = *str++ == '-' ? -1 : 1;
}
int limit = INT_MAX / 10;
int tlimit = INT_MAX % 10;
int res = 0;
for (; *str >= '0' && *str <= '9'; str++) {
if (res > limit || res == limit && *str - '0' > tlimit) {
return sign == 1 ? INT_MAX : INT_MIN;
}
res = res * 10 + (*str - '0');
}
return sign * res;
}
C Solution 2:
int myAtoi(char* str) {
while (*str == ' ') str++;
int sign = 1;
if (*str == '+') str++;
else if (*str == '-') str++, sign = -1;
long val = 0;
while (*str <= '9' && *str >= '0') {
val = val * 10 + *str++ - '0';
if (val * sign > INT_MAX) return INT_MAX;
if (val * sign < INT_MIN) return INT_MIN;
}
return val * sign;
}
Summary:
- The difficult part is considering all possible imput cases.
- And what the function should output in different cases should be specified.
- Always try to make code concise.
- 6ms, 28.54%
LeetCode: 8. String to Integer (atoi)





近期评论