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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int dot_cnt_e = 0;
int e_dot_cnt = 0;
int flag_cnt_e = 0;
int e_flag_cnt = 0;
bool has_number_e = false;
bool e_has_number = false;
bool has_e = false;
bool start = false;
const char* p = s;
while (*p) {
if (invalid_char(*p)) {
return false;
}
if (*p == ' ' && start && !(*(p+1) == ' ' || *(p+1) == '\0')) {
return false;
}
if (*p == '+' || *p == '-') {
if (has_number_e && *(p-1) != 'e') {
return false;
}
if (is_digit(*(p-1)) || *(p-1) == '.') {
return false;
}
if (has_e) {
++e_flag_cnt;
} else {
++flag_cnt_e;
}
if (e_flag_cnt > 1 || flag_cnt_e > 1) {
return false;
}
start = true;
}
if (*p == '.') {
if (!start) {
start = true;
}
if (has_e) {
++e_dot_cnt;
} else {
++dot_cnt_e;
}
if (e_dot_cnt > 0 || dot_cnt_e > 1) {
return false;
}
}
if (*p == 'e') {
if (has_e) {
return false;
} else {
has_e = true;
}
if (!is_digit(*(p+1)) && *(p+1) != '+' && *(p+1) != '-') {
return false;
}
if (!has_number_e) {
return false;
}
}
if (is_digit(*p)) {
if (!start) {
start = true;
}
if (!has_number_e) {
has_number_e = true;
}
if (has_e && !e_has_number) {
e_has_number = true;
}
}
++p;
}
if (has_e) {
return e_has_number;
} else {
return has_number_e;
}
}
private:
bool invalid_char(char ch) {
return !(ch == 'e' || ch == '.' || ch == '+' || ch == '-' || ch == ' ' || is_digit(ch));
}
bool is_digit(char ch) {
return ch >= '0' && ch <= '9';
}
};