Online Judge Solutions

Friday, November 21, 2014

Valid Number

Valid Number
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.

 
// Sol1 http://www.mitbbs.com/article_t1/JobHunting/32787241_0_2.html
class Solution {
public:
    bool isNumber(const char *s) {
       if (!s) return false;
      
       while(*s == ' ')
         s++;
       
       // sign
       if (*s == '+' || *s == '-')
         s++;
        
       int n = getDigits(s);
      
       if (*s == '.') {
           s++;
           n += getDigits(s);
       }
      
       // digits before and after '.' must > 0, ".1" is valid
       if (n < 1) return false;
      
       if (*s == 'e') {
          s++;
          if (*s == '+' || *s == '-')
            s++;
          n = getDigits(s);
          if (n < 1) return false;
       }
      
       // trailing spaces is fine.
       while(*s == ' ') s++;
       return *s == NULL;
    }
   
    // count valid digits and move pointer
    int getDigits(const char *&s){
        int count = 0;
        while (*s >='0' && *s <='9'){
            count++;
            s++;
        }
        return count;
    }
};

// http://n00tc0d3r.blogspot.com/2013/06/valid-number.html
class Solution {
public:
    bool isNumber(const char *s) {
       int fsm[][9] = { 
                     {0, 8, -1, -1, 8, -1, -1, 8, 8}, 
                     {2, -1, -1, -1, -1, 6, -1, -1, -1}, 
                     {1, 1, 1, 4, 4, 7, 7, 7, -1}, 
                     {3, 4, 3, -1, -1, -1, -1, -1, -1}, 
                     {-1, 5, -1, -1, 5, -1, -1, -1, -1} 
                   }; 
        int state = 0;
        while(*s)
        {
            int in = getInput(s);
            if (in < 0) return false;
            state = fsm[in][state];
            if (state < 0) return false;
            s++;
        }
        return state == 1 || state == 4 || state == 7 || state == 8;
    }
   
    // Space(0), Sign(1), Digit(2), Dot(3), Exp(4), Else(-1); 
    int getInput(const char *s) {
        int out = -1;
        switch (*s) {
            case ' ': return 0;
            case '+':
            case '-': return 1;
            case '.': return 3;
            case 'e': return 4;
        }
       
        if (*s >='0' && *s <='9') return 2;
       
        return -1;
    }
};

No comments:

Post a Comment