问题:给出一个字符串,判断它是否是一个有效的数字。
什么叫有效的数字呢?
整数 ,小数 "2.5",正数 "+25",负数"-25",科学计数法"-2e1+0"。
特殊用例:
“.5”, “5.” 认为是有效数字。
无效用例:
“.", "e25", "25e", "2e5e5", "2.5.5", "2e2.5"
输入检查:左右两端出现空格是允许的,内部不能有空格。
- class Solution {
- public:
- bool isNumber(const char *s) {
- if(s == NULL)
- return false;
- int ex, dot;
- ex = dot = 0; // only once
- while(*s == ' ') // space
- s++;
- if(*s == '+' || *s == '-') // sign
- s++;
- if(isNum(*s)) // first char is numeric
- s++;
- else if(*s == '.') // if first char is '.'
- {
- s++;
- dot = 1;
- if(isNum(*s)) // then second char has to be numeric
- s++;
- else
- return false;
- }
- else
- return false;
- while(*s != '\0')
- {
- if(*s == '.')
- {
- if(ex == 1 || dot == 1)
- return false;
- dot = 1;
- }
- else if(*s == 'e')
- {
- if(ex == 1)
- return false;
- ex = 1;
- if(*(s+1) == '+' || *(s+1) == '-') //sign for exponent
- s++;
- if(!isNum(*(s+1))) // numeric after 'e'
- return false;
- }
- else if(*s == ' ') // space has to be on the right side
- {
- break;
- }
- else if(!isNum(*s)) //other letter
- {
- return false;
- }
- s++;
- }
- while(*s == ' ') // space
- s++;
- if(*s == '\0')
- return true;
- else
- return false;
- }
- bool isNum(const char c)
- {
- return (c >= '0' && c <= '9'); // 0<=c<=9
- }
- };
class Solution {
public:
bool isNumber(const char *s) {
if(s == NULL)
return false;
int ex, dot;
ex = dot = 0; // only once
while(*s == ' ') // space
s++;
if(*s == '+' || *s == '-') // sign
s++;
if(isNum(*s)) // first char is numeric
s++;
else if(*s == '.') // if first char is '.'
{
s++;
dot = 1;
if(isNum(*s)) // then second char has to be numeric
s++;
else
return false;
}
else
return false;
while(*s != '\0')
{
if(*s == '.')
{
if(ex == 1 || dot == 1)
return false;
dot = 1;
}
else if(*s == 'e')
{
if(ex == 1)
return false;
ex = 1;
if(*(s+1) == '+' || *(s+1) == '-') //sign for exponent
s++;
if(!isNum(*(s+1))) // numeric after 'e'
return false;
}
else if(*s == ' ') // space has to be on the right side
{
break;
}
else if(!isNum(*s)) //other letter
{
return false;
}
s++;
}
while(*s == ' ') // space
s++;
if(*s == '\0')
return true;
else
return false;
}
bool isNum(const char c)
{
return (c >= '0' && c <= '9'); // 0<=c<=9
}
};