0%

String to Integer

问题描述

Example 1:

1
2
Input: "42"
Output: 42

Example 2:

1
2
3
4
Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

Example 3:

1
2
3
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

1
2
3
4
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

1
2
3
4
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (−231) is returned.

解决方案

主要就是要考虑的细节比较多,特殊的情况及其处理在注释中给出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
int myAtoi(string str)
{
int len = str.length();
int s = 0;
long long res = 0;
int numLen = 0;
bool minus = false;
bool hasNum = false;
while (s < len && ((str[s] == ' ' && !hasNum) || str[s] == '0'))
{
//第二个条件针对"0 123"
if (str[s] == '0')hasNum = true;
++s;
}
if (!hasNum)
{//hasNum的判断针对"0-1"
//if-else语句针对"-+1","-+1","+1"
if (str[s] == '-') { ++s; minus = true; }
else if (str[s] == '+') { ++s; }
}
while (s < len && (str[s] == '0'))++s;//针对" +0 123","-000000000000001"," 0000000000012345678"
if (str[s]<'0' || str[s]>'9')return 0;
while (s < len&&str[s] >= '0' && str[s] <= '9'&&numLen<11)
{//INT_MAX是10位数,numLen针对"20000000000000000000"
res *= 10;
res += (str[s] - '0');
++s; ++numLen;
}
if (minus)res *= (-1);
if (res > INT_MAX)return INT_MAX;
if (res < INT_MIN) return INT_MIN;
return res;
}

另外看到一个解决方法,在处理数字串前面的空白、0、正负号时更简洁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int myAtoi(string str) {
bool neg = false, caled = false;
int res = 0;
int tmp;
for(string::iterator it=str.begin(); it!=str.end(); ++it) {
if ( *it == ' ' && !caled) continue;
if ( *it == '-' && !caled) { neg = true; caled = true; continue; }
if ( *it == '+' && !caled) { neg = false; caled = true; continue; }
if ( *it >= '0' && *it <= '9') {
tmp = *it - '0';
caled = true;
if ( res > 0 && !neg &&
(( res > INT_MAX / 10) || ((INT_MAX - res*10) < tmp)) ) {
res = INT_MAX;
return res;}
if (res > 0 && neg &&
(( -1 * res < INT_MIN / 10) || (res*-10 <= INT_MIN + tmp)) ) {
res = INT_MIN;
return res;}
res = res*10 + tmp;
continue;
}
break;
}
if (caled) res = neg ? -1 * res : res;
return res;
}
};