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.
bool isNumber(const char *s) {
int n = strlen(s);
int i = 0;
while(i<n && (s[i] == ' ' || s[i] == '\t'))i++;
if(i==n)return false;
int j = n-1;
while (j >= 0 && (s[j] == ' ' || s[j] == '\t'))j--;
s = s+i;
n = j-i+1;
if (n == 1)if(s[0] <='9' && s[0] >= '0')return true; else return false;
if (s[0] == '-' || s[0] == '+'){s++;n--;}
if (s[n-1] == '+' || s[n-1] == '-')return false;
bool res = true, dot = false, exp = false, number = false, sign = false;
for (i = 0; i < n; i++)
{
if(i==0 && (s[i] == '+' || s[i] == '-')){return false;}
else if ((s[i] == '+' || s[i] == '-') && s[i-1] != 'e') {return false;}
else if (s[i] == '+' || s[i] == '-')if(sign)return false; else sign = true;
else if(s[i] == '.'){
if (exp == true)return false;
if(dot == false)dot = true;
else return false;
}
else if (s[i] == 'e')
{
if (dot == true && number == false)return false;
if (i==0 || i== n-1 || exp == true)return false;
exp = true;
}
else if (s[i] < '0' || s[i] > '9'){return false;}
else number = true;
}
if(number == false)return false;
return res;
}