An 8ms C solution


  • 0
    G

    21 minutes of trial and error, lol

    bool isNumber(char* s) {
        bool seenFirstDigit = false;
        bool allowExponent = false;
        bool allowDecimal = true;
        bool allowSign = true;
        bool intermediarySpace = false;
        bool requiresDigit = false; 
        while (*s == ' '){
            s++;
        }
        while (*s != 0) {
            if (intermediarySpace) {
                if (*s != ' ') {
                    return false;
                }
            }
            if (!seenFirstDigit) {
                if (*s >= '0' && *s <= '9') {
                    seenFirstDigit = allowExponent = true;
                    allowSign = false;
                }
            }
            if (*s < '0' || *s > '9') {
                if (*s == '.') {
                    if (!allowDecimal) {
                        return false;
                    } 
                    else {
                        allowDecimal = false;
                        allowSign = false; 
                    }
                }
                else if (*s == '-' || *s ==  '+') {
                    if (!allowSign) {
                        return false;
                    }
                    else {
                        allowSign = false; 
                    }
                }
                else if (*s == 'e') {
                    if (!allowExponent) {
                        return false;
                    }
                    else {
                        allowExponent = false;
                        allowDecimal = false; 
                        allowSign = true;
                        requiresDigit = true;
                    }
                }
                else if (*s == ' ') {
                    intermediarySpace = true;
                    s++;
                    continue;
                }
                else {
                    return false;
                }
            }
            else {
                if (requiresDigit) {
                    requiresDigit = false;
                    allowSign = false; 
                }
            }
            s++;
        }
        if (requiresDigit) {
            return false;
        }
        return seenFirstDigit;
    }

Log in to reply
 

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