Two expressions and a clear C++ solution, 8ms


  • 2
    R

    There are two possible expressions for this problem:

    1. bs* sign d+ [dot d*] [e sign d+] bs*
    2. bs* sign [d*] dot d+ [e sign d+] bs*

    The part in [ ... ] is alternative.

    class Solution {
    public:
        void getBs(string& s, int& i){
            while(i<s.length() && s[i] == ' ') 
                ++i;
        }
        void getSign(string& s, int &i){
            if(i<s.length() && (s[i]=='+' || s[i]=='-'))
                i++;
        }
        bool getDigit(string& s, int&i){
            int j=i;
            while(i<s.length() && isdigit(s[i]))
                ++i;
            return (i!=j);
        }
        bool getDot(string& s, int&i){
            if(i<s.length() && s[i]=='.')
                i++;
        }
        bool getE(string& s, int&i){
            if(i<s.length() && (s[i]=='e' || s[i]=='E'))
                i++;
        }
        bool isNumber(string s) {
            int i=0;
            bool integer=false,decimal=false;
            getBs(s, i);
            getSign(s,i);
            // getBs(s,i);
            if(getDigit(s,i)){
                integer = true;
            }
            
            if(getDot(s,i)){
                if(getDigit(s,i)) 
                    decimal = true;
            }
            if(getE(s,i)){
                getSign(s,i);
                if(!getDigit(s,i)) return false;
            }
            getBs(s,i);
            if(i!= s.length()) return false;
            if(integer == false &&  decimal==false) return false;
            return true;
        }
    };

Log in to reply
 

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