Validate if a given string is numeric.
Have you met this question in a real interview?
Yes
Example
"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
LeetCode上的原题,请参见我之前的博客Valid Number。
class Solution {
public:
/**
* @param s the string that represents a number
* @return whether the string is a valid number
*/
bool isNumber(string& s) {
bool num = false, numAfterE = true, dot = false, exp = false, sign = false;
int n = s.size();
for (int i = ; i < n; ++i) {
if (s[i] == ' ') {
if (i < n - && s[i + ] != ' ' && (num || dot || exp || sign)) return false;
} else if (s[i] == '+' || s[i] == '-') {
if (i > && s[i - ] != 'e' && s[i - ] != ' ') return false;
sign = true;
} else if (s[i] >= '' && s[i] <= '') {
num = true;
numAfterE = true;
} else if (s[i] == '.') {
if (dot || exp) return false;
dot = true;
} else if (s[i] == 'e') {
if (exp || !num) return false;
exp = true;
numAfterE = false;
} else return false;
}
return num && numAfterE;
}
};