Simple c solution that implements a Regular expression


  • 0
    L
    // /^\s*[+-]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)(e[+-]?[0-9]+)?\s*$/
    
    bool isNumber(char* s) {
        // skip white spaces
        while (*s != '\0' && *s == ' ') ++s;
        
        // optional sign
        if (*s == '+' || *s == '-') ++s;
        
        int startWithDot = 0;
        if (*s == '.') {
            startWithDot = 1;
            ++s;
        }
        
        // parse one or more digits
        char* s0 = s;
        while (*s != '\0' && *s >= '0' && *s <= '9') ++s;
        if (s0 == s) return false;
        
        // if haven't seen . yet, parse digits (zero or more) after the decimals point.
        if (startWithDot == 0 && *s == '.') {
            ++s;
            while (*s != '\0' && *s >= '0' && *s <= '9') ++s;
        }
        
        // parse scientfic notation
        if (*s == 'e') {
            ++s;
            if (*s == '+' || *s == '-') ++s;
            
            s0 = s;
            while (*s != '\0' && *s >= '0' && *s <= '9') ++s;
            if (s0 == s) return false;
        }
        
        // skip white spaces
        while (*s != '\0' && *s == ' ') ++s;
        
        return *s == '\0';
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.