8ms C++ solution, easy to understand.


  • 3
    B

    This solution goes through the front to the back.

    1. Skip leading spaces.

    2. Skip sign bit.

    3. Integer, decimal point and fractional parts (make sure at least one digit exists)

    4. Exponential bit. (There may be sign bits again and make sure there is digit following)

    5. Skip following spaces.

    6. Make sure that's the end.

        bool isNumber(string s)
        {
            int n = s.size();
            if(n == 0) return false;
            
            int i = 0;
            //Skip leading spaces.
            while(s[i] == ' ') i++;
            
            //Significand
            if(s[i] == '+' || s[i] == '-') i++;
            
            int cnt = 0;
            //Integer part
            while(isdigit(s[i]))
            {
                i++;
                cnt++;
            }
            //Decimal point
            if(s[i] == '.') i++;
            //Fractional part
            while(isdigit(s[i]))
            {
                i++;
                cnt++;
            }
            if(cnt == 0) return false;  //No number in front or behind '.'
            
            //Exponential
            if(s[i] == 'e')
            {
                i++;
                if(s[i] == '+' || s[i] == '-') i++;
                if(!isdigit(s[i])) return false;    //No number follows
                while(isdigit(s[i])) i++;
            }
            
            //Skip following spaces;
            while(s[i] == ' ') i++;
            
            return s[i] == '\0';
        }

  • 0
    D

    "Integer, decimal point and fractional parts (make sure at least one digit exists)"

    The test cases have "3." being OK. Doesn't that violate your code?


  • 0
    B

    No actually. In my code, I count for digits both before and after the decimal point (if there is one), so "3." is absolutely ok.


  • 0
    D

    Cool, thanks! Nice work.


Log in to reply
 

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