1. 前导后导空格去掉。若出现空格将字符串截成两段的情况,返回false. 将结果压入string对象中
2. 遍历string, 若出现非数字,非加减号,非小数点,非e的情况,返回false.
3. 若出现e, 判断e前和e后的字串(str.substr(0, pos)和str.substr(pos+1))是否合法(注意到e后的字串不能有小数点)
4. 若没出现e, 判断str是否合法即可。
代码:
class Solution
{
public:
bool isNumber(const char *s)
{
string str;
size_t pos = string::npos;
bool begin_space=true, number_finish=false;
// 去掉前导后导空格
for (int i = 0; i < strlen(s); ++ i)
{
if (s[i] == ' ')
{
if (begin_space == true)
{
continue;
} else
{
number_finish = true;
}
} else if(number_finish == false) // s[i]!=' '
{
begin_space = false;
str.push_back(s[i]);
} else
{
return false;
}
}
// 判断是否有非法字符,同时寻找e,注意到第二次找到e将返回false
for (size_t i = 0; i < str.size(); ++ i)
{
if (str[i]=='e' && pos==string::npos)
{
pos = i;
} else if (str[i]!='-' && str[i]!='+' && str[i]!='.'
&& (str[i]<'0'||str[i]>'9'))
{
return false;
}
}
if (pos==str.size()-1) // last character is 'e'
{
return false;
} else if (pos == string::npos) // no 'e'
{
return gao(str, 1);
} else
{
return gao(str.substr(0, pos), 1) && gao(str.substr(pos+1), 0);
}
}
private:
bool gao(const string& str, int dot_available)
{
int dot_cnt = 0;
bool has_digit=false;
for (int i = 0; i <str.size(); ++ i)
{
dot_cnt = str[i]=='.'? dot_cnt+1: dot_cnt;
if (i!=0 && (str[i]=='+'||str[i]=='-'))
{
return false;
} else if (str[i]>='0' && str[i]<='9')
{
has_digit = true;
}
}
return dot_cnt<=dot_available && has_digit;
}
};