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.
1:符号共有六种情况,非法输入,空格,+/-, 0~9数字,小数点, e/E;2:采用有穷状态机,根据某个状态以及当前的输入判断下一个状态是什么;3:+/-, 小数点,e/E只能出现一次。4:有穷状态机中状态和输入的状态表列出, 5:最后根据停止的状态来判断是不是非法的输入
bool isNumber(const char *s)
{
if(s == NULL || *s == '\0')
{
return false;
}
enum InputType{
INVALID,
SPACE,
SIGN,
DIGIT,
DOT,
EXPONENT,
};
int stateTable[][6]
{
-1, 0, 3, 1, 2, -1,
-1, 8, -1, 1, 4, 5,
-1, -1, -1, 4, -1, -1,
-1, -1, -1, 1, 2, -1,
-1, 8, -1, 4, -1, 5,
-1, -1, 6, 7, -1, -1,
-1, -1, -1, 7, -1, -1,
-1, 8, -1, 7, -1, -1,
-1, 8, -1, -1, -1, -1,
};
int state = 0;
while(*s)
{
InputType input = INVALID;
if(*s == ' ')
{
input = SPACE;
}
else if(*s == '+' || *s == '-')
{
input = SIGN;
}
else if(*s >= '0' && *s <= '9')
{
input = DIGIT;
}
else if(*s == '.')
{
input = DOT;
}
else if(*s == 'e' || *s == 'E')
{
input = EXPONENT;
}
state = stateTable[state][input];
if(state == -1)
{
return false;
}
++s;
}
if(state ==1 || state == 4 || state == 7 || state == 8)
{
return true;
}
else
{
return false;
}
}