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.
Solution:Code:
<span style="font-size:14px;">class Solution {
public:
bool isDigit(const char &c) {
int temp = c - '0';
if ((0 <= temp) && (temp <= 9))
return true;
return false;
}
bool isWithoutSign (const char *s, int &index) {
int countE = 0;
int countP = 0;
bool containBlank = false;
bool containDigit = false;
bool containSign = false;
bool beforeE = false;
bool afterE = false;
bool beforeP = false;
bool afterP = false;
for (int i = index; i < strlen(s); i++) {
if (s[i] == 'e') {
if (containBlank) return false;
countE++;
if (countE > 1) return false;
} else if (s[i] == '.') {
if (containBlank) return false;
if (countE) return false;
countP++;
if (countP > 1) return false;
} else if (isDigit(s[i])) {
if (containBlank) return false;
containDigit = true;
if (!countP) beforeP = true;
else afterP = true;
if (!countE) beforeE = true;
else afterE = true;
} else if ((s[i] == '+') || (s[i] == '-')) {
if (containBlank) return false;
if (containSign) return false;
if (s[i-1] != 'e') return false;
containSign = true;
} else if (s[i] == ' ') {
containBlank = true;
} else {
return false;
}
}
if ((countE) && (!(beforeE && afterE))) return false;
if ((countP) && (!(beforeP || afterP))) return false;
if (!containDigit) return false;
return true;
}
bool isNumber(const char *s) {
bool result = false;
int index = 0;
while ((s[index] == ' ')) {
index++;
}
if ((s[index] == '+') || (s[index] == '-')) {
index++;
result = isWithoutSign(s, index);
} else {
result = isWithoutSign(s, index);
}
return result;
}
};</span>