8ms solution C++, easy understand with comment


  • 0
    O
    class Solution {
    public:
        bool isNumber(string s) {
            int i=0, n = s.size();
            for(;s[i]==' ';i++);
            if(s[i]=='-'||s[i]=='+') i++;
            
            int a = countInt(s, i), b=0;
            if(s[i]=='.'){
                i++;
                b = countInt(s, i);
            }
            
            // if none digit begin
            if(a+b==0) return false;
            
            if(s[i]=='e'){
                i++;
                if(s[i]=='-'||s[i]=='+') i++;
                if(countInt(s, i)==0) return false; // if no digit after 'e'
            }
            for(;s[i]==' ';i++);
            
            return i==s.size();
        }
        
        int countInt(string& s, int& i){
            int ret=0;
            for(;isdigit(s[i]);ret++,i++);
            return ret;
        }
    };

Log in to reply
 

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