It is not easy to write this function correctly, because there are many things to consider:
1) There may be spaces before and after the string, but spaces are not allowed in the middle.
2) There may be decimal places, 1.235, or. 3522.
3) There may be exponential forms, 2e10 2e-1 AND OTHER FORMS
Validate if a given string is Numeric.
Some examples:
"0"
=>true
" 0.1 "
=>true
"abc"
=>false
"1 a"
=>false
"2e10"
=>true
There are many restrictions to consider whether the string is in the numerical form. Therefore, we can use the form of a global variable to indicate whether this numeric form is valid again.
Then, query by bit to check whether the prerequisite debugging is true. If one of the conditions is not met, false is returned.
<span style="font-size:18px;">class Solution {public: bool isNumber(const char *s) { while (*s == ' ') ++s; while (*s == '+' || *s == '-') ++s; bool exp = false, space = false, point = false; bool number = false; while (*s != '\0') { if (isdigit(*s)) { if (space) return false; else number = true; } else if (*s == '.') { if (!point && !space && !exp) { point = true; } else { return false; } } else if (*s == 'e') { if (!exp && number && !space) { exp = true; number = false; while (*(s+1) == '+' || *(s+1) == '-') ++s; } else { return false; } } else if (*s == ' ') { if (!space) { space = true; } } else { return false; } ++s; } return number; }};</span>
Forty-seven daily algorithms: valid number (verify whether it is a number)