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: This finite-state machine solution. Learn from fuwutu & snakeDling.
1 class Solution { 2 public: 3 bool isNumber(const char *s) { 4 enum InputType {INVALID, SPACE, SIGN, DIGIT, DOT, EXPONENT}; 5 int transitionTable[][6] = 6 { /* 0 1 2 3 4 5 */ 7 0, 1, 2, 3, 4, 0, // 0: INVALID 8 0, 1, 2, 3, 4, 0, // 1: SPACE 9 0, 0, 0, 3, 4, 0, // 2: SIGN 10 0, 6, 0, 3, 7, 5, // 3: DIGIT 11 0, 0, 0, 7, 0, 0, // 4: DOT 12 0, 0, 2, 8, 0, 0, // 5: EXPONENT 13 0, 6, 0, 0, 0, 0, // 6: END WITH SPACE 14 0, 6, 0, 7, 0, 5, // 7: DOT AND DIGIT 15 0, 6, 0, 8, 0, 0, // 8: END WITH SPACE OR DIGIT 16 }; 17 18 InputType last = INVALID; 19 while (*s != '