题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
class Solution {
public:
bool isNumeric(char* string)
{
int i = 0;
if(string[i]=='+' || string[i]=='-' || IsNum(string[i])){
while(string[++i]!='\0' && IsNum(string[i]));
//后面跟小数点
if(string[i]=='.'){
if(IsNum(string[++i])){
while(string[++i]!='\0' && IsNum(string[i]));
if(string[i]=='e'||string[i]=='E'){
i++;
if(string[i]=='+' || string[i]=='-' || IsNum(string[i])){
while(string[++i]!='\0' && IsNum(string[i]));
if(string[i]=='\0') return true;
else return false;
}else return false;
}else if(string[i]=='\0') return true;
else return false;
}else if(string[++i]=='\0') return true;
else return false;
}
//后面跟e或者E
else if(string[i]=='e'||string[i]=='E'){
i++;
if(string[i]=='+' || string[i]=='-' || IsNum(string[i])){
while(string[++i]!='\0' && IsNum(string[i]));
if(string[i]=='\0') return true;
else return false;
}else return false;
}
else if(string[i]=='\0') return true;
else return false;
}else return false;
}
bool IsNum(char ch)
{
if(ch<'0'||ch>'9') return false;
else return true;
}
};