Problem:
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.
Analysis:
So many cases to consider!
First of all, remove all the space at both ends of the given string;
Now we start from the left.
The first position is a little bit special
1. '+/-': skip them
2. '.': set the dotFlag
3. '0~9': set the numFlag
4. others: invalid input
we continue
if '.' is met, we break out of the current loop, start a new one. Note after '.', only 'e', numbers are allowed.
if 'e' is met, break out of the current loop, start a new one. Note after 'e', only numbers or '+/-' are allowed
Code:
1 class Solution { 2 public: 3 bool isNumber(const char *s) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int idx = 0, len = strlen(s)-1; 7 bool dotFlag = false, numFlag = false, eFlag=false; 8 9 if (s=="") return false; 10 11 while (s[idx] == ' ') idx++; 12 if (idx > len) return false; 13 14 while (s[len] == ' ') len--; 15 16 17 if (s[idx] == '+' || s[idx] == '-') idx++; 18 19 if (idx > len) return false; 20 21 int i; 22 for (i=idx; i<=len; i++) { 23 if (s[i] == 'e') { 24 i += 1; 25 eFlag = true; 26 break; 27 } 28 29 if (s[i] == '.') { 30 i += 1; 31 dotFlag = true; 32 break; 33 } 34 35 if (s[i]>='0' && s[i]<='9') { 36 numFlag = true; 37 } else { 38 return false; 39 } 40 41 } 42 43 44 if (dotFlag) { 45 if (!numFlag && (i>len || ((s[i]<'0' && s[i]>'9') && s[i]!='e'))) 46 return false; 47 48 for (; i<=len; ++i) { 49 if (s[i] <'0' || s[i] > '9') { 50 if (s[i] == 'e') { 51 i+= 1; 52 eFlag = true; 53 break; 54 } else { 55 return false; 56 } 57 } 58 59 numFlag = true; 60 } 61 } 62 63 //number after e 64 if (eFlag) { 65 if (!numFlag) return false; 66 67 if (i==idx+1 || i>len) return false; 68 69 if (s[i] == '+' || s[i] == '-') 70 i += 1; 71 72 if (i > len) return false; 73 74 for (; i<=len; i++) { 75 if (s[i]<'0' || s[i]>'9') 76 return false; 77 } 78 } 79 80 81 return true; 82 } 83 };
Attention: