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)
本文介绍了一个C++实现的字符串到数字的解析方法,通过三个核心函数isNumber、isDecimal和isInteger完成对输入字符串的有效判断。代码首先去除字符串两端空白字符,并检查字符串是否为空,然后针对'e'或'E'进行特殊处理,分别判断小数部分和整数部分的有效性。
572

被折叠的 条评论
为什么被折叠?



