# Keep a state machine in mind and everything will work out properly.

• I passed this problem with one single submission, though I found a few bugs myself before my submission.

``````class Solution {
public:
bool isNumber(string s, int state = -1) {
if (state == -1)
{
if (s.empty()) return false;
int i = 0, j = s.size() - 1;
for (;i < s.size() && isspace (s[i]); ++i);
for (;j >= 0 && isspace (s[j]); --j);
return isNumber(s.substr(i, j - i + 1), 0);
}
if (state == 0)
{
if (s.empty()) return false;
if (s[0] == '-' || s[0] == '+')
return isNumber(s.substr(1), 1);
return isNumber(s, 1);
}
if (state == 1)
{
if (s.empty()) return false;
int i = 0;
for (;i < s.size() && isdigit(s[i]); ++i);
if (i == s.size())
return true;
if (s[i] == '.')
{
if (i > 0)
return isNumber(s.substr(i+1), 2);
return isNumber(s.substr(i+1), 20);
}
if (s[i] == 'e')
{
if (i > 0)
return isNumber(s.substr(i+1), 3);
return false;
}
return false;
}
if (state == 2)
{
if (s.empty()) return true;
int i = 0;
for (;i < s.size() && isdigit(s[i]); ++i);
if (i == s.size())
return true;
if (s[i] == 'e')
return isNumber(s.substr(i + 1), 3);
return false;
}
if (state == 20)
{
if (s.empty()) return false;
int i = 0;
for (;i < s.size() && isdigit(s[i]); ++i);
if (i == 0)
return false;
if (i == s.size())
return true;
if (s[i] == 'e')
return isNumber(s.substr(i + 1), 3);
return false;
}
if (state == 3)
{
if (s.empty()) return false;
if (s[0] == '-' || s[0] == '+')
return isNumber(s.substr(1), 4);
return isNumber(s, 4);
}
if (state == 4)
{
if (s.empty()) return false;
for (int i = 0; i < s.size(); ++i)
if (!isdigit(s[i]))
return false;
return true;
}
return false;
}
};``````

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