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.
题意:判断是一个字符串是不是合法的数字,数字可以是小数
分析:这道题隐含了很多条件,我也是WA了无数次才试出来的。。包括:
(1)忽略前导空格和后缀空格,中间部分必须是合法数字
(2)数字可以以‘+’,‘-’开头
(3)小数点只能出现一次,但是小数点之前或之后可以没有数字(一边有数字即可)
(4)e只能出现一次,左右必须都有数字,e左侧可以是小数(也就是说左边相邻字符可能是小数点),右侧必须是整数(但是可以以‘+’,‘-’开头)
代码:
class Solution {
public:
bool isNum(char c)
{
if(c>='0' && c<='9') return true;
return false;
}
bool isNumber(const char *s) {
int len = strlen(s);
if(len==0) return false;
int pos = 0;
while(s[pos]==' ') pos++;
if(pos>=len) return false;
int st=pos;
if(s[st]=='-' || s[st]=='+') st++;
bool isdot=false,ise=false;
for(pos=st; pos<len && s[pos]!=' '; pos++)
{
if(isNum(s[pos]))
continue;
else if(s[pos]=='.')
{
if(isdot) return false;
isdot = true;
int now=0;
if(pos>st && isNum(s[pos-1])) now++;
if(pos<len-1 && isNum(s[pos+1])) now++;
if(now<1) return false;
}
else if(s[pos]=='e')
{
if(ise) return false;
ise = true;
isdot = true;
int now=0;
if(pos>st && (isNum(s[pos-1]) || s[pos-1]=='.')) now++;
if(pos<len-1)
{
if(s[pos+1]=='+'||s[pos+1]=='-')
{
pos++;
if(pos<len-1 && isNum(s[pos+1])) now++;
}
else if(isNum(s[pos+1]))
now++;
}
if(now<2) return false;
}
else
return false;
}
for(; pos<len; pos++)
if(s[pos]!=' ') return false;
return true;
}
};