[LeetCode] 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.
spoilers alert... click to show requirements for atoi.
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.
1 class Solution { 2 public: 3 enum Status {VALID, INVALID}; 4 Status g_isvalid = INVALID; 5 6 int atoi(const char *str) { 7 unsigned long long result = 0; 8 if (str == NULL) { 9 return result; 10 } 11 12 13 while (*str != '\0' && *str == ' ') 14 ++str; 15 16 int sign = 1; 17 if (*str == '+') { 18 ++str; 19 } else if (*str == '-') { 20 sign = -1; 21 ++str; 22 } 23 24 while (*str != '\0') { 25 if (*str >= '0' && *str <= '9') { 26 g_isvalid = VALID; 27 result = result * 10 + (*str - '0'); 28 if (result > INT_MAX) 29 return sign == 1 ? INT_MAX : INT_MIN; 30 ++str; 31 } else { 32 break; 33 } 34 } 35 36 37 return sign * result; 38 } 39 };
思路:要注意的细节较多
1)输入为空指针、空字符串""、只有一个正负号、字符串中全是空格、没有有效输入的情况下要设置无效标记,返回值为0。
2)忽略开头空格字符,并且对第一个非空格字符做‘+’,‘-’号的判断(可选,不是必须)
3)如果碰到不是数字的字符,则停止转换
4)如果正溢出,则返回INT_MAX,如果负溢出则返回INT_MIN
5)如果第一个非空字符串不是有效的数字(只对第一个非空字符串判断),或者字符串中只有空格,那么返回0。
时间复杂度O(n),空间复杂度O(1)
相关题目:《剑指offer》面试题49