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 isNumber(const char *s) {
if (s == NULL) return false;
int str_len = strlen(s);
if (str_len == 0) return false;
const char *ptr = s;
int start = 0, end = str_len;
while (*ptr != '\0' && *ptr == ' ') {
++ptr;
++start;
}
ptr = s + str_len - 1;
while (ptr >= s && *ptr == ' ') {
--ptr;
--end;
}
if (start > end) return false;
string ss(s + start, end - start);
if (string::npos != ss.find("e")) {
return isValidExp(ss);
}
if (string::npos != ss.find(".")) {
return isValidFloat(ss);
}
return isValidInt(ss, 1);
}
private:
bool isValidExp(string s) {
size_t e_pos = s.find("e");
string left_str = s.substr(0, e_pos);
string right_str = s.substr(e_pos + 1, s.length() - e_pos - 1);
if (left_str.length() == 0 || right_str.length() == 0) return false;
return isValidFloat(left_str) && isValidInt(right_str, 1);
}
bool isValidFloat(string s) {
if (s[0] == '+' || s[0] == '-') { //去除开头的正负号
s = s.substr(1, s.length()-1);
}
size_t pt_pos = s.find(".");
string left_str = s.substr(0, pt_pos);
string right_str = s.substr(pt_pos + 1, s.length() - pt_pos - 1);
if (left_str.length() == 0 && right_str.length() == 0) return false;
if (left_str.length() == 0 && isValidInt(right_str, 0)) return true;
if (isValidInt(left_str, 1) && right_str.length() == 0) return true;
return isValidInt(left_str, 1) && isValidInt(right_str, 0);
}
bool isValidInt(string s, int is_left) {
bool ret = false;
if (s.length() == 0) {
return false;
}
string::iterator it;
for (it = s.begin(); it != s.end(); ++it) {
if (it == s.begin() && (*it == '+' || *it == '-') && is_left) {
continue;
}
if (*it >= '0' && *it <= '9') {
ret = true;
} else {
ret = false;
break;
}
}
return ret;
}
};