-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathvalid_number.cpp
35 lines (28 loc) · 881 Bytes
/
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
class Solution {
public:
bool isNumber(string s)
{
int i = 0;
// skip the whilespaces
for(; s[i] == ' '; i++) {}
// check the significand
if(s[i] == '+' || s[i] == '-') i++; // skip the sign if exist
int n_nm, n_pt;
for(n_nm=0, n_pt=0; (s[i]<='9' && s[i]>='0') || s[i]=='.'; i++)
s[i] == '.' ? n_pt++:n_nm++;
if(n_pt>1 || n_nm<1) // no more than one point, at least one digit
return false;
// check the exponent if exist
if(s[i] == 'e') {
i++;
if(s[i] == '+' || s[i] == '-') i++; // skip the sign
int n_nm = 0;
for(; s[i]>='0' && s[i]<='9'; i++, n_nm++) {}
if(n_nm<1)
return false;
}
// skip the trailing whitespaces
for(; s[i] == ' '; i++) {}
return s[i]==0; // must reach the ending 0 of the string
}
};