# C++ O(n) solution with clean decomposition

• ``````class Solution {
private:
bool getNum(string& s, int& pos, bool allowSign) {          // return value: if found valid digits or not
bool isNum = false;
if (allowSign && pos < s.length() && (s[pos] == '+' || s[pos] == '-')) { pos++; }   // skip '+'/'-'
for (; pos < s.length() && isdigit(s[pos]); pos++) { isNum = true; }                // found digits
return isNum;
}

public:
bool isNumber(string s) {
int pos = 0;                                            // position in string

while (pos < s.length() && s[pos] == ' ') { pos++; }    // skip initial spaces

bool isNum = getNum(s, pos, true);                      // extract first number. isNum: if we've found any number
if (pos < s.length() && s[pos] == '.') {
pos++;                                              // skip '.' if any
isNum |= getNum(s, pos, false);                     // extract second number if any
}

if (pos < s.length() && s[pos] == 'e') {
pos++;                                              // skip 'e' if any
if (!getNum(s, pos, true)) { return false; }        // must have a number following 'e' if 'e' exists
}

while (pos < s.length() && s[pos] == ' ') { pos++; }    // skip ending spaces

return isNum && pos == s.length();                      // number has to exist and s has to be completely processed
}
};
``````

• This post is deleted!

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