# Very simple c++ sol (Not a DFA sol)

• The idea is to TRY go through the string and see if we can finally arrive at the end of string or not. In the middle we return false if two cases happen:

``````1. there is no number at all
2. after e/E there is no integer
``````

I grouped codes into small functions and give them recognizable names so that it is easier to see the pattern:

``````class Solution {
public:
bool isNumber(const char *s) {
skipSpace(s);
skipSign(s);
if(!hasNumber(s)) return false; // there's no number at all so return false

if(*s!='\0' && (*s=='e' || *s=='E')) {
s++;
skipSign(s);
if(!hasInteger(s)) return false; // after e/E no integer then return false
}
skipSpace(s);
return *s=='\0';
}
private:
void skipSpace(const char*& s) {
while(*s!='\0' && *s==' ') s++;
}
void skipSign(const char*& s) {
if(*s!='\0' && (*s=='+' || *s=='-')) s++;
}
// returns true if has a number like 7, 8., 9.1, 0.8, ...
bool hasNumber(const char*& s) {
int len = 0;
while(*s!='\0' && isdigit(*s)) {s++; len++;}
if(*s!='\0' && *s=='.') s++;
while(*s!='\0' && isdigit(*s)) {s++; len++;}
return len!=0;
}
// returns true if has an integer
bool hasInteger(const char*& s) {
int len = 0;
while(*s!='\0' && isdigit(*s)) {s++; len++;}
return len!=0;
}

};``````

• very clean code. thanks for sharing

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