Tried 12 times, lower than average, so sad


  • 0
    M

    The code is just ugly, no more words.

    bool isNumber(const char *s) {
    
        int start = 0;
        int end = strlen(s) - 1;
        // either side could have spaces, strip the spaces of the two ends
    
        while (s[start] == ' ') {
            start++;
        }
    
        while (s[end] == ' ') {
            end--;
        }
    
        if (start > end) {
            return false;
        }
    
        unsigned int cnt_dot  = 0;
        unsigned int cnt_e    = 0;
        unsigned int cnt_dig_dot = 0;
        unsigned int cnt_dig_e   = 0;
    
        bool digi_before_dot = false;
        bool digi_before_e   = false;
    
        for (int i = start; i <= end; ++i) {
    
            switch (s[i]) {
                case '.': {
                    // can not appear after e
                    if (cnt_e) {
                        return false;
                    }
    
                    // can not have multiple dots
                    if (cnt_dot) {
                        return false;
                    }
    
                    digi_before_dot = (cnt_dig_dot > 0);
    
                    cnt_dot++;
                    cnt_dig_dot = 0;
    
                    break;
                }
                case 'e': {
                    // can not have multiple e
                    if (cnt_e) {
                        return false;
                    }
    
                    // have digits before it
                    digi_before_e = (cnt_dig_e > 0);
    
                    cnt_e++;
    
                    cnt_dig_e = 0;
                    break;
                }
                case '+':
                case '-': {
                    // should appear at the start
                    if (i != start) {
                        // or right after 'e'
                        if (!(cnt_e && (s[i-1] == 'e'))) {
                            return false;
                        }
                    }
                    break;
                }
                default: {
                    if (   (s[i] < '0')
                        || (s[i] > '9')) {
                        return false;
                    }
                    else {
                        cnt_dig_dot++;
                        cnt_dig_e++;
                    }
                }
            }
        }
    
        bool digi_after_e = (cnt_e && cnt_dig_e);
        bool digi_after_dot = (cnt_dot && cnt_dig_dot);
    
        if (cnt_e) {
            return digi_before_e && digi_after_e;
        }
    
        if (cnt_dot) {
            return digi_before_dot || digi_after_dot;
        }
    
        return true;
    }

  • 0
    S

    Take this as reference.


Log in to reply
 

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