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.
这样的问题无力吐槽
class Solution {
public:
bool isNumber(const char *s) {
if( s == NULL || s == '\0')
return false;
bool flag = true;
string str = "";
int pos = 0;
while( s[pos] == ' ')
++pos;
for( int i = pos; s[i] != '\0'; ++i){
if( isalpha(s[i])){
if( s[i] != 'e' && s[i] != 'E')
return false;
else{
if( flag){
flag = false;
str += s[i];
}
else
return false;
}
}
else if( isdigit(s[i]))
str += s[i];
else if( iscntrl(s[i]))
return false;
else if( ispunct(s[i])){
if( s[i] == '.' || s[i] == '-' || s[i] == '+')
str += s[i];
else
return false;
}
else
str += s[i];
}
int cnt = 0;
int punct = 0;
int num = 0;
flag = true;
for( int i = 0; i < str.size(); ++i){
if( isdigit(str[i])){
num = num * 10 + ( str[i] - '0');
++cnt;
}
if( str[i] == 'e' || str[i] == 'E'){
flag = false;
if( num == 0 && str[0] != '0')//.e
return false;
if( i + 1 == str.size())//8e
return false;
else if( !isdigit(str[i+1]))//8e.
if(str[i+1] != '+' && str[i+1] != '-')//32.e-80
return false;
else
;
}
if( str[i] == '.'){
if( flag)//8e.
++punct;
else
return false;
}
if( str[i] == '+' || str[i] == '-'){//3-2
if( i != 0){
if( str[i-1] != 'e' && str[i-1] != 'E')//8e2+2
return false;
else if( i + 1 == str.size())//4e+
return false;
}
}
}
flag = true;
for( int i = str.size() - 1; i >= 0; --i){
if( isspace(str[i]) || isblank(str[i])){
if(!flag)
return false;
}
else
flag =false;
}
if( !cnt || punct > 1)
return false;
return true;
}
};