文章目录
  1. 1. Valid Number

Valid Number


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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
bool isNumber(string s) {
int startIndex = 0;

//先忽视掉空格
for (int i = 0; i < s.size(); i++)
{
if (s[i] != ' ')
{
startIndex = i;
break;
}
}

//消掉之前的正负号
if (s[startIndex] == '+' || s[startIndex] == '-')
startIndex++;

//从忽视掉空格后的字符开始判断
bool result = false;
bool isSpaceFound = false; //在表达式中是否发现空格
bool isEFound = false; //在表达式中是否发现e
bool symbolBehindEFound = false; //e之后的符号已经被定位
bool isNumFound = false; //是否发现数字
bool isDotFound = false;
bool isNumBehindEFound = false; //e后的数字是否存在

for (int i = startIndex; i < s.size(); i++)
{
if (s[i] == ' ')
isSpaceFound = true;
else if ((s[i] >= '0' && s[i] <= '9') || s[i] == 'e' || s[i] == '+' || s[i] == '-' || s[i] == '.')
{
if (isSpaceFound)
break;

if (s[i] >= '0' && s[i] <= '9')
{
isNumFound = true;

if (isEFound)
isNumBehindEFound = true;
}

if (s[i] == '+' || s[i] == '-')
{
if (!isEFound)
break;

if (symbolBehindEFound) //多个符号
break;

if (s[i - 1] != 'e') //符号前应是e
break;

symbolBehindEFound = true;
}

if (s[i] == '.')
{
if (isEFound) //e后不能有.
break;

if (isDotFound) //.只能一次
break;

isDotFound = true;
}

if (s[i] == 'e')
{
if (!isNumFound) //e前必须有数字
break;

if (isEFound) //只能有一个e
break;

isEFound = true;
}
}
else
break;

if (i == s.size() - 1)
{
if(isNumFound)
result = true;

if (isEFound && !isNumBehindEFound)
result = false;
}
}

return result;
}
文章目录
  1. 1. Valid Number