Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
本题需要考虑:
1、字符前的空格
2、字符正负号
3、检查是否是数字,数字中可以包含一个‘.’小数点,数字至少应存在一位
4、略过数字和点后,检查是否有‘e’,如果有:
(1)检查指数是否有正负
(2)检查其后是否有数字,数字至少存在一位
5、字符后的空格
6、最后遇到'\0'则返回true,否则false
代码:
class Solution {
public:
bool isNumber(string s) {
int i = ; // 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=, n_pt=; (s[i]<='' && s[i]>='') || s[i]=='.'; i++)
s[i] == '.' ? n_pt++:n_nm++;
if(n_pt> || n_nm<) // 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 = ;
for(; s[i]>='' && s[i]<=''; i++, n_nm++) {}
if(n_nm<)
return false;
} // skip the trailing whitespaces
for(; s[i] == ' '; i++) {} return s[i]==; // must reach the ending 0 of the string
}
};