class Solution {
public:
bool isNumber(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s == NULL) return false;
if (strlen(s) == 0) return false;
int begin = 0;
int end = strlen(s) - 1;
while (s[begin] == ' ') ++begin;
while (s[end] == ' ') --end;
if (begin > end) return false;
int idx = begin;
while (idx <= end)
{
if (s[idx] == 'e' || s[idx] == 'E')
return isDecimal(s, begin, idx - 1) && isInteger(s, idx + 1, end);
++idx;
}
return isDecimal(s, begin, end);
}
bool isDecimal(const char* s, int begin, int end)
{
if (begin <= end)
{
int idx = begin;
bool hasDot = false;
bool hasDigit = false;
if (s[idx] == '+' || s[idx] == '-')
++idx;
while (idx <= end)
{
if (s[idx] >= '0' && s[idx] <= '9')
{
++idx;
hasDigit = true;
continue;
}
else if (s[idx] == '.')
{
if (!hasDot)
{
++idx;
hasDot = true;
continue;
}
else
return false;
}
else
return false;
}
return hasDigit;
}
return false;
}
bool isInteger(const char* s, int begin, int end)
{
if (begin <= end)
{
int idx = begin;
bool hasDigit = false;
if (s[idx] == '+' || s[idx] == '-')
++idx;
while (idx <= end)
{
if (s[idx] >= '0' && s[idx] <= '9')
{
++idx;
hasDigit = true;
}
else
return false;
}
return hasDigit;
}
return false;
}
};
注: 参照qingli代码写出 (http://blog.youkuaiyun.com/maqingli87/article/details/8010737)