problem:
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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
thinking:
(1)细节处理题,注意‘E’ 和 ‘e’的大小写
(2)空格判断函数 isspace(char*)可以调用,减少工作量
code:
通过版本:参考http://www.cnblogs.com/remlostime/archive/2012/11/18/2775938.html,注意参数char *s ,而不是string,之前的版本
我自己的版本:未通过,原因(1)leetcode 判断'.1'和"1."也是有效数字(2)大小写'e‘ 'E'没注意区分(3)...
class Solution {
public:
bool isNumber(string s) {
int n=s.size();
if(n==0)
return false;
if(n==1)
{
if(s.at(0)>='0' && s.at(0)<='9')
return true;
else
return false;
}
if(s.at(0)==' ')
{
string::iterator start=s.begin();
string::iterator end=start;
while(*end==' ')
end++;
s.erase(start,end);
return isNumber(s);
}
if(s.at(n-1)==' ')
{
string::iterator end=s.end();
string::iterator start=end-1;
while(*start==' ')
start--;
s.erase(++start,end);
return isNumber(s);
}
if(s.at(0)=='+' || s.at(0)=='-')
{
s.erase(s.begin(),s.begin()+1);
return isNumber(s);
}
int count1=0;
int index1=0;
int count2=0;
int index2=0;
int count3=0;
for(int i=0;i<n;i++)
{
if((s.at(i)>='0'&&s.at(i)<='9') || s.at(i)=='.' || s.at(i)=='e' )
{
if(s.at(i)=='.')
{
count1++;
index1=i;
}
else if(s.at(i)=='e')
{
count2++;
index2=i;
}
else
count3++;
}
else
return false;
}//for
if(count3==n)
return true;
if(count1>1 || count2>1)
return false;
if(count2==1)
{
if(index2==0 || index2==n-1)
return false;
else
return check2(s,index2);
}
if(count1==1)
{
if(index1==0 ||index1==n-1)
return false;
else
return check1(s,index1);
}
}
protected:
bool check1(string s, int loc) //小数不含e
{
for(int i=0;i<loc;i++)
if(s.at(i)>'9' || s.at(i)<'0')
return false;
for(int j=loc+1;j<s.size();j++)
if(s.at(j)>'9' || s.at(j)<'0')
return false;
return true;
}
bool check2(string s, int loc)//科学计数
{
bool flag1=true, flag2=true;
int count=0;
int index=0;
for(int i=0;i<loc;i++)
{
if(s.at(i)=='.')
{
count++;
index=i;
continue;
}
if(s.at(i)<'0' || s.at(i)>'9')
return false;
}
if(count>1)
return false;
if(count==1)
{
string tmp(s,0,loc);
if(!check1(tmp,index))
return false;
}
/*前半部分检查完毕*/
for(int j=loc+1;j<s.size();j++)
{
if(s.at(loc+1)=='+' || s.at(loc+1)=='-')
continue;
if(s.at(j)<'0' || s.at(j)>'9')
return false;
}
return true;
}
};