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.
T.T WA得快哭了,总是想的太少。。最终提交了十几次才确定了下来。
干扰物有 e, 空格, 正负号,小数点,文法见注释。
/*
* Number = fnum, fnum e dnum, ' ' + Number + ' ', -Number.
* fun(float number) = dnum, dnum., .dnum, dnum . dnum.
* dnum(digit number) = digit, digit + dnum. Notice : not null.
*/
class Solution {
public:
bool isNumber(const char *s) {
// deal with ' ' and (+-)
while (*s == ' ')
++s;
if (*s == '-' || *s == '+')
++s;
int len = strlen(s);
while (s[len - 1] == ' ')
--len;
if (len <= 0)
return false;
// look for 'e'
const char *ptr = strchr(s, 'e');
if (ptr) {
int len1 = ptr - s;
int len2 = len - len1 - 1;
if (*(ptr + 1) == '+' || *(ptr + 1) == '-') {
++ptr;
--len2;
}
return (isFnum(s, len1) && isDnum(ptr + 1, len2));
}
else
return isFnum(s, len);
}
bool isFnum(const char *s, int len) {
// cout << "f" << s << endl << len << endl;
// look for '.'
const char *ptr = strchr(s, '.');
if (ptr) {
if (ptr - s == 0)
return isDnum(s + 1, len - 1);
if (ptr - s == len - 1)
return isDnum(s, len - 1);
else
return (isDnum(s, ptr - s)
&& isDnum(ptr + 1, len - (ptr - s) - 1) );
}
else
return isDnum(s, len);
}
bool isDnum(const char *s, int len) {
if (!len) return false;
// cout << "d" << s << endl << len << endl;
const char *p = s;
for (int i = 0; i < len; ++i, ++p) {
if (!isdigit(*p))
return false;
}
return true;
}
};