Problem
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、"-1E-16"、“0123"都表示数值,但"12e”、“1a3.14”、“1.2.3”、"±5"及"12e+5.4"都不是。
Solution
class Solution {
public:
bool isNumber(string s
) {
int l
= 0, r
= s
.size() - 1;
while (l
<= r
&& s
[l
] == ' ')
l
++ ;
while (l
<= r
&& s
[r
] == ' ')
r
-- ;
if (l
> r
)
return false;
s
= s
.substr(l
, r
- l
+ 1);
if (s
[0] == '+' || s
[0] == '-')
s
= s
.substr(1);
if (s
.empty())
return false;
if (s
[0] == '.' && (s
.size() == 1 || s
[1] == 'e' || s
[1] == 'E'))
return false;
int dot
= 0, e
= 0;
for (int i
= 0; i
< s
.size(); i
++ )
{
if (s
[i
] == '.')
{
if (dot
> 0 || e
> 0)
return false;
dot
++ ;
}
else if (s
[i
] == 'e' || s
[i
] == 'E')
{
if (!i
|| i
+ 1 == s
.size() || e
> 0)
return false;
if (s
[i
+ 1] == '+' || s
[i
+ 1] == '-')
{
if (i
+ 2 == s
.size())
return false;
i
++ ;
}
e
++ ;
}
else if (s
[i
] < '0' || s
[i
] > '9')
return false;
}
return true;
}
};
转载请注明原文地址:https://tech.qufami.com/read-1621.html