0%

把字符串转换成整数

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
int StrToInt(string str) {
if (str.size() == 0)
{
return 0;
}
else
{
auto it = str.begin();
int result = 0, symbol;
switch (*it)
{
case '-':
symbol = -1;
it++;
break;
case '+':
symbol = 1;
it++;
break;
default:
if (*it >= '0' && *it <= '9')
{
symbol = 1;
}
else
{
return 0;
}
}
for (; it != str.end(); it++)
{
if (*it >= '0' && *it <= '9')
{
result *= 10;
result += (*it - '0');
}
else
{
return 0;
}
}
return symbol * result;
}
}
};