Very easy and clear solution in C++.


  • 0
    C
    bool isNumber(string s) {
        trim(s);
        if (s.empty()) {
            return false;
        }
    
        int i = 0;
        for (i = 0; i < s.size(); ++i) {
            if (s[i] == 'e') {
                break;
            }
        }
    
        if (i == s.size()) {
            return isDecimal(s);
        } else {
            if (i == 0) {
                return false;
            } else if (i == s.size() - 1) {
                return false;
            } else {
                return isDecimal(s.substr(0, i)) && isInteger(s.substr(i + 1, s.size() - 1 - i));
            }
        }
    }
    
    string& trim(string &s) 
    {
        if (s.empty()) 
        {
            return s;
        }
    
        s.erase(0,s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
        return s;
    }
    
    bool isInteger(string s) {
        if (s.empty()) {
            return false;
        }
    
        if (s[0] == '+' || s[0] == '-') {
            return isUnsignedInteger(s.substr(1, s.size() - 1));
        } else {
            return isUnsignedInteger(s);
        }
    }
    
    bool isDecimal(string s) {
        if (s.empty()) {
            return false;
        }
    
        if (s[0] == '+' || s[0] == '-') {
            return isUnsignedDecimal(s.substr(1, s.size() - 1));
        } else {
            return isUnsignedDecimal(s);
        }
    }
    
    bool isUnsignedInteger(string s) {
        if (s.empty()) {
            return false;
        }
    
        set<char> numbers;
        for (char c = '0'; c <= '9'; ++c) {
            numbers.insert(c);
        }
    
        int i = 0;
        while (i < s.size() && numbers.find(s[i]) != numbers.end()) {
            ++i;
        }
    
        return i == s.size();
    }
    
    bool isUnsignedDecimal(string s) {
        if (s.empty()) {
            return false;
        }
    
        int i = 0;
        for (i = 0; i < s.size(); ++i) {
            if (s[i] == '.') {
                break;
            }
        }
    
        if (i == s.size()) {
            return isUnsignedInteger(s);
        } else {
            if (i == 0) {
                return isUnsignedInteger(s.substr(1, s.size() - 1));
            } else if (i == s.size() - 1) {
                return isUnsignedInteger(s.substr(0, i));
            } else {
                return isUnsignedInteger(s.substr(0, i)) && isUnsignedInteger(s.substr(i + 1, s.size() - 1 - i));
            }
        }
    }

Log in to reply
 

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