[Rainbow] A more concise and clearer C++ implementaiton with detailed comments


  • 3
    class Solution {
    public:
        bool isNumber(string s) {
            int i=0, n=s.size();
            /** skip space **/
            while(s[i]==' ') i++;
            /** get sign **/
            if(s[i]=='+' || s[i]=='-')  i++;
            /** check number and points **/
            int c1=0;
            while(i<n && s[i]>='0' && s[i]<='9') { i++;  c1++; }
            if(i<n && s[i]=='.')  i++;
            while(i<n && s[i]>='0' && s[i]<='9') { i++;  c1++; }
            if(c1==0)  return false;
            /** check exponent parts **/
            if(s[i]=='e') {
                i++;
                if(s[i]=='+' || s[i]=='-')  i++;
                c1=0;
                while(s[i]>='0' && s[i]<='9')  { i++; c1++; }
                if(c1<1)  return false;
            }
            /** skip space **/
            while(s[i]==' ') i++;
            return i==n;
        }
    };

  • 0

    Attention to use s[i]>='0' && s[i]<='9'

    I code with s[i]>='0' && s[i]<=9

    23333333333333


  • 1

    I miss to add the i++ after checking the s[i]=='e' and type the '9' as 9.

    The result ........ You know.......

    The trouble I have meet is all about details ....

    class Solution {
    public:
        bool isNumber(string s) {
            int i=0, n=s.size();
            while(s[i]==' ') i++;
            if(s[i]=='-' || s[i]=='+')  i++;
            int c=0;
            while(s[i]>='0' && s[i]<='9') { i++; c++; }
            if(s[i]=='.')  i++;
            while(s[i]>='0' && s[i]<='9') { i++; c++; }
            if(c==0)  return false;
            if(s[i]=='e'){
                i++; /** I miss this **/
                if(s[i]=='-' || s[i]=='+')  i++;
                c=0;
                while(s[i]>='0' && s[i]<='9') { i++; c++; }
                if(c==0)  return false;
            }
            while(s[i]==' ') i++;
            return i==n;
        }
    };

Log in to reply
 

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