Looking for Shortest Possible C++ Solution


  • 1
    K

    As C++ is kinda less capable of string processing. I would like to know what is the shortest or cleanest solution in C++, regardless of time/memory complexity.

    My first AC version was a huge piece of code, processing the string character by character. Then I came up with the following. I know there must be neater solutions. Please do not hesitate pasting yours.

    class Solution {
    public:
    bool isNumber(const char *s) {
        while(*s == ' ')    //trim preceding spaces
            s++;
        string str(s);
        while(str.back() == ' ')    //trim ending spaces
            str.pop_back();
        if (str.empty()) return false;
        bool dig = false;
        for (int i=0; i<str.length(); i++)
            if (isdigit(str[i]))
            {
                dig = true;
                break;
            }
        if (!dig) return false; //no actual number exists
        if (!isdigit(str.back()) && str.back()!='.')
            return false;  //only allow ending number and '.'
        stringstream ss(str);
        long double dbl;
        ss >> dbl;
        if (ss.rdstate() & stringstream::eofbit)
            return true;
    
        return false;
    }
    };

  • 1
    R

    Hi, although your code passed the oj, but actually it is incorrect. Consider this test case: ".E10", which is not a valid num, but the result of your algorithm is true.


  • 0
    L

    .E10 is indeed a valid number, it is basically 0.00000000001


  • 0
    A

    actually, I failed the case, .e10.


  • 0
    W

    I think you are in the wrong direction. Because you have tried to use others's code to solve your problem. You have to handle the error yourself.


  • 0
    A
    This post is deleted!

Log in to reply
 

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