-
Notifications
You must be signed in to change notification settings - Fork 28
/
Valid_Number.cpp
58 lines (51 loc) · 1.66 KB
/
Valid_Number.cpp
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
class Solution {
public:
bool isNumber(string s) {
if (s.empty())
return false;
int n = (int)s.length();
int i = 0;
while(i < n and isspace(s[i])) {
++i;
}
if (s[i] == '+' || s[i] == '-')
i++;
bool eAppear = false;
bool dotAppear = false;
bool firstPart = false;
bool secondPart = false;
bool spaceAppear = false;
while(i < n) {
if (s[i] == '.') {
if (dotAppear || eAppear || spaceAppear)
return false;
dotAppear = true;
} else if (s[i] == 'e' || s[i] == 'E') {
if (eAppear || !firstPart || spaceAppear)
return false;
eAppear = true;
} else if (isdigit(s[i])) {
if (spaceAppear)
return false;
if (!eAppear)
firstPart = true;
else
secondPart = true;
} else if (s[i] == '+' || s[i] == '-') {
if (spaceAppear)
return false;
if (!eAppear || !(s[i - 1] == 'e' || s[i - 1] == 'E'))
return false;
} else if (isspace(s[i]))
spaceAppear = true;
else
return false;
i++;
}
if (!firstPart)
return false;
if (eAppear && !secondPart)
return false;
return true;
}
};