-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidNumber.cpp
More file actions
39 lines (38 loc) · 1.13 KB
/
validNumber.cpp
File metadata and controls
39 lines (38 loc) · 1.13 KB
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
// Source: https://leetcode.com/problems/valid-number/
// Author: Miao Zhang
// Date: 2021-01-13
class Solution {
public:
bool isNumber(string s) {
if (s.empty()) {
return false;
}
int i = 0, j = s.size() - 1;
while (i <= j && s[i] == ' ') i++;
while (j >= 0 && s[j] == ' ') j--;
bool is_digit = false, is_dot = false, is_e = false;
for (;i <= j; i++) {
if (s[i] >= '0' && s[i] <= '9') {
is_digit = true;
} else if (s[i] == '-' || s[i] == '+') {
if (i != 0 && s[i - 1] != 'e' && s[i - 1] != 'E') {
return false;
}
} else if (s[i] == '.') {
if (is_dot || is_e) {
return false;
}
is_dot = true;
} else if (s[i] == 'e' || s[i] == 'E') {
if (not is_digit || is_e) {
return false;
}
is_digit = false;
is_e = true;
} else {
return false;
}
}
return is_digit;
}
};