Skip to content

Commit 5a54240

Browse files
committed
Valid Number update
1 parent b79e832 commit 5a54240

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

65.cpp

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
class Solution {
2+
public:
3+
bool isNumber(string s) {
4+
bool ret = false;
5+
int i = 0;
6+
7+
// space
8+
while(s[i] == 32)
9+
{
10+
++i;
11+
}
12+
13+
// - or +
14+
if(s[i] == 45 || s[i] == 43)
15+
{
16+
++i;
17+
}
18+
19+
int len = s.size();
20+
21+
bool hasDot = false;
22+
bool hasE = false;
23+
bool hasPart1 = false;
24+
bool hasPart2 = false;
25+
26+
for(; i < len; ++i)
27+
{
28+
// .
29+
if(s[i] == 46 )
30+
{
31+
if(hasDot || hasE || (i == 0 && i == len - 1))
32+
{
33+
return false;
34+
}
35+
else
36+
{
37+
hasDot = true;
38+
}
39+
40+
}
41+
// e
42+
else if(s[i] == 101)
43+
{
44+
if(hasE || !hasPart1)
45+
{
46+
return false;
47+
}
48+
else
49+
{
50+
hasE = true;
51+
52+
}
53+
}
54+
// number
55+
else if(s[i] >= 48 && s[i] <= 57)
56+
{
57+
if (!hasE)
58+
{
59+
hasPart1 = true;
60+
}
61+
else
62+
{
63+
hasPart2 = true;
64+
}
65+
}
66+
// - or +
67+
else if(s[i] == 45 || s[i] == 43)
68+
{
69+
if (!hasE || !(s[i-1] == 101))
70+
return false;
71+
}
72+
// space
73+
else if(s[i] == 32)
74+
{
75+
while(s[i] == 32)
76+
{
77+
++i;
78+
}
79+
break;
80+
}
81+
else
82+
{
83+
return false;
84+
}
85+
}
86+
87+
if (!hasPart1)
88+
{
89+
return false;
90+
}
91+
else if (hasE && !hasPart2)
92+
{
93+
return false;
94+
}
95+
else if (i != len)
96+
{
97+
return false;
98+
}
99+
else
100+
{
101+
return true;
102+
}
103+
}
104+
};

0 commit comments

Comments
 (0)