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.
题意:判断一个string是否是有效数字。
难度是hard,这个hard不在于有多难写,而在于有很多莫名其妙的有效数字。“这样都行!?”“你是在逗我吗???”“到底有完没完!”各种奇葩数字层出不穷,就这样在补漏洞的过程中竟然AC了~o(╯□╰)o~凸
总结了一下数字特性如下:
1、字符串前后可以存在空格,中间不可以有
2、字母只可以有e(我只判断了小写没有判断大写竟然也可以,或者说默认为只有小写才正确?)
3、e前后一定要有非0的数字
4、e后面不可以有小数点
5、e与小数点之间要有数字
6、e后面可以有+或-(+、-前面一定要为e)
7、最后一个字符不可以为’+’ 、’-‘和 ‘e’
8、e和小数点 . 只可以出现一次
其实规则没有这么复杂,只是在一次次补漏洞中越来越多。
bool isNumber(string s) {
if(s.length()==0)
{
return false;
}
int i=0;
while(i<s.length()&&s[i]==' ')
{
i++;
}
if(i==s.length())
{
return false;
}
int j=s.length()-1;
while(j>=i&&s[j]==' ')
{
--j;
}
if(s[i]=='+'||s[i]=='-')
{
i++;
}
stack<char> st;
bool e=false;
bool d=false;
bool al=false;
int len=j-i+1;
while(i<=j)
{
if(s[i] >='0' && s[i] <='9')
{
if(s[i]>'0'&&!e)
{
al=true;
}
if(s[i]>'0'&&e)
{
al=true;
}
st.push(s[i]);
}
else if(s[i]=='.'&&!e&&!d)
{
st.push(s[i]);
d=true;
}
else if(s[i]=='e'&&!e)
{
if(st.empty())
{
return false;
}
else if(st.top()=='.'&&!al)
{
return false;
}
st.push(s[i]);
e=true;
}
else if(s[i]=='+'||s[i]=='-')
{
if(!st.empty())
{
if(st.top()=='e')
{
st.push(s[i]);
}
else{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
i++;
}
if(e&&!al)
{
return false;
}
if(st.top()=='e'||st.top()=='+'||st.top()=='-')
{
return false;
}
if(len==1&&st.top()=='.')
{
return false;
}
return true;
}