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.
» Solve this problembool isNumber(const char *s) {
while(*s == ' ') s++;
bool isNum = false;
bool hasOp = false;
bool hasExp = false;
bool hasDot = false;
bool hasNum = false;
for(; *s!='\0'; s++)
{
if(*s == '+' || *s == '-')
{
if(!hasOp && !hasNum)
{
hasOp=true;
isNum = false;
continue;
}
else
{
isNum = false;
break;
}
}
if(*s == '.')
{
if(!hasDot)
{
hasDot=true;
hasNum=true;
if(hasExp)
{
isNum = false;
break;
}
continue;
}
else
{
isNum = false;
break;
}
}
if(*s == 'e')
{
if(!hasExp && hasNum)
{
hasExp=true;
hasOp = false;
hasNum = false;
isNum = false;
continue;
}
else
{
isNum = false;
break;
}
}
if(*s<='9' && *s>='0')
{
isNum = true;
hasNum = true;
continue;
}
else
{
if(*s != ' ')
{
isNum = false;
break;
}
while(*s == ' ') s++;
if(*s !='\0')
{
isNum = false;
}
break;
}
}
return isNum;
}