65. Valid Number

Validate if a given string is numeric.

Some examples:
"0"=>true
" 0.1 "=>true
"abc"=>false
"1 a"=>false
"2e10"=>true

S: 细节问题,主要是clarify ambiguity

面试时需要问清下面几个case

  1. 字符串首位可以有空格,中间不可以有空格

    1. 字符串的格式是(+/-)x.y e(+/-)n

    2. x,y不可以同时为空串,n不可以为空串

    3. x, n可以以多个0开始,y可以以0结束

    bool isNumber(string s) {
        int i = 0;
        bool hasNum = false, usedE = false;
        //skip beginning space
        while (s[i] == ' ') i++;
        //optional: check sign
        if (s[i] == '+' || s[i] == '-') i++;
        if (checkDigit(s, i)) hasNum = true;
        //optional: check decimal
        if (s[i] == '.') i ++;
        hasNum |= checkDigit(s, i);
        //optional: check e
        if (s[i] == 'e') {
            i++;
            usedE = true;
        }
        //optional: check exponent sign
        if (s[i] == '+' || s[i] == '-') {
            if (usedE) {
                i++;
            } else {
                return false;
            }
        }
        //e must followed by the exponent num
        if (usedE && !checkDigit(s, i)) return false;
        //skip tailing space
        while (s[i] == ' ') i++;
        //make sure reach the end and has num in the string
        return i == s.size() && hasNum;
    }

    bool checkDigit(string s, int& i) {
        bool hasDigit = false;
        while (isdigit(s[i])) {
            hasDigit = true;
            i++;
        }
        return hasDigit;
    }

results matching ""

    No results matching ""