首页 > 代码库 > LeetCode --- 8. String to Integer (atoi)
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.
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.
这道题的要求是将字符串转化成整数。
思路是逐个字符处理,比较简单。可能需要考虑以下几个问题:
前导空格:忽略前面空格,直到正号、负号或者数字才开始转化。
额外字符:如果数字后面有额外的非数字字符,同样忽略。即转化直到第一个非数字字符之前。
溢出问题:和Reverse Integer的处理思路一样,再结果乘以10之前判断是否大于INT_MAX/10(即214748364)。不同之处是等于INT_MAX/10时,需要判断下一字符是否大于或等于8,因为INT_MAX = 2147483647。
时间复杂度:O(n)
空间复杂度:O(1)
1 class Solution
2 {
3 public:
4 int atoi(const char *str)
5 {
6 int i, s = 0, sign = 1;
7
8 for(i = 0; str[i] == ‘ ‘; ++ i);
9
10 if(str[i] == ‘-‘)
11 {
12 ++i;
13 sign = -1;
14 }
15 else if(str[i] == ‘+‘)
16 ++i;
17
18 while(str[i] >= ‘0‘ && str[i] <= ‘9‘)
19 {
20 if(s > INT_MAX / 10 || s == INT_MAX / 10 && str[i] >= ‘8‘)
21 return sign == 1 ? INT_MAX : INT_MIN;
22 s = s * 10 + (str[i++] - ‘0‘);
23 }
24
25 return sign * s;
26 }
27 };
转载请说明出处:LeetCode --- 8. String to Integer (atoi)
LeetCode --- 8. String to Integer (atoi)