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.
class Solution {
public:
bool isInvalid(char ch)
{
if (ch == '+' || ch == '-' || ch == '.' || ch == 'e' )
return false;
if (ch >= '0' && ch <= '9')
return false;
return true;
}
bool isNumber(const char *s) {
string str(s);
str = str.erase(0,str.find_first_not_of(" "));
str = str.erase(str.find_last_not_of(" ") + 1);
bool hasDot = false;
bool hasDigit = false;
bool hasExp = false;
bool hasSign = false;
if (str.size() == 0)
return false;
int len = str.size();
for (int i=0; i<len; i++)
{
if (isInvalid(str[i]))
return false;
if (str[i] == '+' || str[i] == '-')
{
// +-号 不能在最后,如果不是在最前头,则一定要跟在e后
if (str[i+1] == '\0' || i!= 0 && str[i-1] != 'e')
return false;
else
hasSign = true;
}
else if (str[i] == '.')
{
// 字符串不能只有一个. 同时.之前不能.有或者e,如果.在最后则前面必须要有数字
if (len == 1 || hasDot || hasExp || (!hasDigit && str[i+1] == '\0'))
return false;
else
hasDot = true;
}
else if (str[i] == 'e')
{
// e不能在最前头和最后,如果前面有e或者没有数字也不行
if (i == 0 || str[i+1] == '\0' || !hasDigit || hasExp)
return false;
else
hasExp = true;
}
else
{
hasDigit = true;
}
}
return true;
}
};