Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
class Solution {
private:
//1234
bool isonlydigits(const string& s,int l,int r)
{
if(l>r) return false;
for(int i=l;i<=r;i++)
if(s[i]<'0' || s[i]>'9') return false;
return true;
}
//+ -
bool isnum(const string& s,int l,int r)
{
if(l>r)return false;
if(s[l]=='+' || s[l]=='-') return isnum(s,l+1,r);
return isonlydigits(s,l,r);
}
//0.22
bool isposfloat(const string& s,int l,int r)
{
if(l>r)return false;
if(s[l]=='.') return isonlydigits(s,l+1,r);
if(s[r]=='.') return isonlydigits(s,l,r-1);
for(int i=l+1;i<=r-1;i++)
if(s[i]=='.')
return isonlydigits(s,l,i-1) && isonlydigits(s,i+1,r);
return isonlydigits(s,l,r);
}
//+- 0.22
bool isfloat(const string& s,int l,int r)
{
if(l>r)return false;
if(s[l]=='+' || s[l]=='-') return isposfloat(s,l+1,r);
return isposfloat(s,l,r);
}
public:
bool isNumber(const char *s)
{
//trim
string str="";
int len=strlen(s);
int l=0;
while(l<len && s[l]==' ') l++;
int r=len-1;
while(r>=0 && s[r]==' ') r--;
for(int i=l;i<=r;i++)
str=str+s[i];
//only 1-9 . e + -
for(int i=0;i<str.length();i++)
{
if(str[i]>='0' || str[i]<='9' || str[i]=='.'
|| str[i]=='+' || str[i]=='-' || str[i]=='e' || str[i]=='E')
{
}
else return false;
}
//split by e
for(int i=0;i<str.length();i++)
if(str[i]=='e' || str[i]=='E')
{
return isfloat(str,0,i-1) && isnum(str,i+1,str.length()-1);
}
//no e
return isfloat(str,0,str.length()-1);
}
};
private:
//1234
bool isonlydigits(const string& s,int l,int r)
{
if(l>r) return false;
for(int i=l;i<=r;i++)
if(s[i]<'0' || s[i]>'9') return false;
return true;
}
//+ -
bool isnum(const string& s,int l,int r)
{
if(l>r)return false;
if(s[l]=='+' || s[l]=='-') return isnum(s,l+1,r);
return isonlydigits(s,l,r);
}
//0.22
bool isposfloat(const string& s,int l,int r)
{
if(l>r)return false;
if(s[l]=='.') return isonlydigits(s,l+1,r);
if(s[r]=='.') return isonlydigits(s,l,r-1);
for(int i=l+1;i<=r-1;i++)
if(s[i]=='.')
return isonlydigits(s,l,i-1) && isonlydigits(s,i+1,r);
return isonlydigits(s,l,r);
}
//+- 0.22
bool isfloat(const string& s,int l,int r)
{
if(l>r)return false;
if(s[l]=='+' || s[l]=='-') return isposfloat(s,l+1,r);
return isposfloat(s,l,r);
}
public:
bool isNumber(const char *s)
{
//trim
string str="";
int len=strlen(s);
int l=0;
while(l<len && s[l]==' ') l++;
int r=len-1;
while(r>=0 && s[r]==' ') r--;
for(int i=l;i<=r;i++)
str=str+s[i];
//only 1-9 . e + -
for(int i=0;i<str.length();i++)
{
if(str[i]>='0' || str[i]<='9' || str[i]=='.'
|| str[i]=='+' || str[i]=='-' || str[i]=='e' || str[i]=='E')
{
}
else return false;
}
//split by e
for(int i=0;i<str.length();i++)
if(str[i]=='e' || str[i]=='E')
{
return isfloat(str,0,i-1) && isnum(str,i+1,str.length()-1);
}
//no e
return isfloat(str,0,str.length()-1);
}
};