请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
思路:e后面不能有小数点的出现,出现e后判断下一位是不是数字,不是就为false,小数点出现后判断下一位是不是数字,不是就为false。小数点最多出现1次。e不能做最后一个字符。
class Solution {
public:
bool iseorE(char *str,int &i,int count)
{
i++;
if(i>=count)
return false;
if(str[i]=='+'||str[i]=='-')
i++;
if(str[i]<'0'||str[i]>'9')
return false;
return true;
}
bool ispoint(char *str,int &i,int count)
{
i++;
if(i>=count)
return false;
if(str[i]<'0'||str[i]>'9')
return false;
return true;
}
bool isNumeric(char* str)
{
if(str==NULL)
return false;
int count = strlen(str);
if(count==1)
{
if(!(str[0]<'0'||str[0]>'9'))
return true;
return false;
}
if((str[0]!='+'&&str[0]!='-')&&(str[0]<'0'||str[0]>'9'))
{
return false;
}
int i=1;
int pointer=0;
bool pree = false;
while(i
'9')
{
if(str[i]=='e'||str[i]=='E')
{
pree= true;
if(iseorE(str,i,count))
{
i++;
continue;
}
else return false;
}
if(str[i]=='.')
{
if(pree)
return false;
pointer++;
if(pointer>1)
return false;
if(ispoint(str,i,count))
{
i++;
continue;
}
else return false;
}
else return false;
}
else
{
i++;
}
}
return true;
}
};