Concise C++ solution, very clear flow with explanation


  • 0
    M
    1. signs: ' + ', ' - ', ' e ', ' . ', space (while spaces cannot exist among digits), all other chars would be invalid
    2. ".2" = "0.2" valid, "2." = "2.0" is valid, but empty num is invalid. (ie. "+." / ".e5" / "e5" are invalid numbers)
    3. e cannot followed by frac num

    Basic flow: To divide the number into three parts, each part can only contain a valid integer, whether signed or not.

    Helpful APIs:

    //trim the leading and tailing spaces
    void trimSpaces(string& s); 
    /*
    @param: num - the integer number to check
    @param: canSign - can have leading sign char. (i.e. the part after fraction point cannot)
    @param: canEmpty - if the num can have nothing. (i.e. ".5" is valid, "+" is not valid)
    */
    bool validInt(string num, bool canSign, bool canEmpty); 
    

    The code:

    bool isNumber(string s) {
            trimSpaces(s);
            
            int pose = s.find('e');
            if(pose != string::npos){
                if(!validInt(s.substr(pose + 1), true, false)){
                    return false;
                }
                s.resize(pose); //trim to leave a number without exponent
            }
            
            int pospoint = s.find('.');
            if(pospoint != string::npos){  //to make sure the part before and after point are not empty at the same time
                return (validInt(s.substr(0, pospoint), true, true) && validInt(s.substr(pospoint + 1), false, false)) ||
                (validInt(s.substr(0, pospoint), true, false) && validInt(s.substr(pospoint + 1), false, true));
            }
            return validInt(s, true, false); //if there's no point character, check it as a normal signed integer
        }
        
        void trimSpaces(string& s){
            int pos = s.find_first_not_of(' ');
            if(pos != string::npos){
                s = s.substr(pos);
            }
            pos = s.find_last_not_of(' ');
            if(pos != string::npos){
                s = s.substr(0, pos + 1);
            }
        }
        
        bool validInt(string num, bool canSign, bool canEmpty){
            if(!num.empty() && (num[0] == '+' || num[0] == '-')){
                if(!canSign){
                    return false;
                }
                num = num.substr(1);
            }
            if(num.empty()){
                return canEmpty;
            }
            for(char c : num){
                if(!isdigit(c)){
                    return false;
                }
            }
            return true;
        }
    
    

Log in to reply
 

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