[LeetCode-8] String to Integer (atoi)
String to Integer (atoi)
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.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
考虑到了负数、考虑到了123E3、考虑到了1.23E3、正负溢出这堆东西,靠badcase发现忽略了+符号、前面的空格、还有不支持小写的'e'……wa了几次过了……
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int atoi(const char *str) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 const char* p = str; 7 if (*p == '\0') { 8 return 0; 9 } 10 int fh = 1; 11 bool is_mi = false; 12 int point_pos = 0; 13 bool is_point = false; 14 15 int result = 0; 16 int mi = 0; 17 18 while (' ' == *p) { 19 ++p; 20 } 21 if ('-' == *p) { 22 fh = -1; 23 ++p; 24 } else if ('+' == *p) { 25 ++p; 26 } 27 28 while (*p) { 29 if (*p >= '0' && *p <= '9') { 30 if (is_mi) { 31 if ((double)mi * 10 > INT_MAX) { 32 return fh > 0 ? INT_MAX : INT_MIN; 33 } 34 mi *= 10; 35 if ((double)mi + (*p - '0') > INT_MAX) { 36 return fh > 0 ? INT_MAX : INT_MIN; 37 } 38 mi += (*p - '0'); 39 } else { 40 if ((double)result * 10 > INT_MAX) { 41 return fh > 0 ? INT_MAX : INT_MIN; 42 } 43 result *= 10; 44 if ((double)result + (*p - '0') > INT_MAX) { 45 return fh > 0 ? INT_MAX : INT_MIN; 46 } 47 result += (*p - '0'); 48 if (is_point) { 49 ++point_pos; 50 } 51 } 52 } else if ((!is_mi) && (/*'e' == *p || */'E' == *p)) { 53 is_mi = true; 54 } else if ('.' == *p && !is_mi) { 55 is_point = true; 56 } else { 57 break; 58 } 59 ++p; 60 } 61 mi -= point_pos; 62 while (mi-- > 0) { 63 if ((double)result * 10 > INT_MAX) { 64 return fh > 0 ? INT_MAX : INT_MIN; 65 } 66 result *= 10; 67 } 68 return fh * result; 69 } 70 };