Implement atoi to convert a string to an integer.
Hint:carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.
Notes:it is intended-problem to be specified vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.
Main topic
Implement the Atoi function to convert a string to an integer.
Difficulty factor : Easy
Realize
This is my implementation, passed the Leetcode test.
int atoi (const char *str) {if (strlen (str) = = 0) {return 0; } int i = 0; int val = 0; BOOL sign = false; for (i = 0; Str[i]! = ' + '; ++i) {if (str[i] = = ' | | str[i] = = ') {continue; } break; } if (strlen (str+i) = = 0) {return 0; } if (str[i] = = '-') {sign = true; i++; } for (; Str[i]! = ' + '; ++i) {if (Str[i] < ' 0 ' | | str[i] > ' 9 ') {break; if (sign) {if (val < INT_MIN/10 | | (val = = Int_min/10 && (str[i]-' 0 ') >= int_min% 10 *-1)) return int_min; val = val * ten-(str[i]-' 0 '); } else {if (val > Int_max/10 | | (val = = Int_max/10 && (str[i]-' 0 ') >= int_max% 10)) return Int_max; val = val * + str[i]-' 0 '; }} return Val;
This code, though tested. But after I have someone else's code, I still feel a bit of a problem.
To determine if STR is NULL, this I think can be used, many of the C function is actually the case, you pass a null pointer will crash. As far as this function is concerned, you can pass a null pointer and almost conclude that your code is faulty. This function accepts NULL pointers will segmentation fault, seemingly simple and rough, it is very appropriate, after all, you expect the parameter is not a null pointer, before the function has been a problem, continue to run is not a good way. If you feel the need to consider NULL, then you can add judgment.
Judge the null character, whether it is a number, here I do not call the library function isspace or isdigit to achieve, this is I write bad place. Calling library functions can improve portability.
Leetcode8--string to Integer (atoi)