方法:分为几个部分判断 DA[.B][E/eC] D
其中D表示前后的空格,需要处理,跳过即可
A可以带正负号 有符号数
B无符号数
C可以为有符号数(带+-号)
小数点.后面必须是无符号数或者没有 如1.
同时小数点.前面可以没有数字 所以用numeric = findUnsignedInt(s,pos) || numeric(或)
E/e前后必须有数字 因此用 numeric = numeric && findInt(s,pos)
class Solution {
public:
bool isNumber(string s) {
//DA[.B][E/eC] D
//A可以带正负号 有符号数
//B无符号数
//C有符号数
//处理前面的空格
int pos = 0;
while(s[pos]!='\0' && s[pos]==' ')
{
++pos;
}
//A部分
bool numeric = findInt(s,pos);
//B部分
if(s[pos]=='.')
{
//.后面必须是无符号数或者没有 如1.
//.前面可以没有数字 所以用||
++pos; //看小数点后的呀
numeric = findUnsignedInt(s,pos) || numeric;
}
//C部分
if(s[pos]=='e'||s[pos]=='E')
{
++pos; //看e后面的!!
numeric = numeric && findInt(s,pos);
}
while(s[pos]!='\0' && s[pos]==' ')
{
++pos;
}
return numeric && (s[pos]=='\0');
}
bool findUnsignedInt(const string& s,int& pos)
{
int save = pos;
while(s[pos]!='\0' && s[pos]>='0' && s[pos]<='9')
{
++pos;
}
return pos>save; //说明有数字
}
bool findInt(const string& s,int& pos)
{
//
if( s[pos]=='-' || s[pos]=='+')
{
++pos;
}
return findUnsignedInt(s,pos);
}
};