您的位置:首页 > 其它

LeetCode OJ 之 Valid Number (有效数字的判断)

2015-01-30 11:08 477 查看

题目:

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.
判断给的字符串是否是一个数字。
注意:题目的说明是模棱两可的,你应该考虑到所有可能。

思路:

1、对于空格,只能出现在开始和结尾,如"    123    "。出现在中间则不符合条件,”123 123“。

2、对于+-,只能出现在非空格的首位和e或者E的下一位。比如“   +123” , “123E-10”,最多出现两次。

3、对于. ,可以出现在数字前和数字后,如 ".123",或者”123.“,但是不能出现在e和E后,比如”123E5.“,最多出现一次。

4、对于e和E,只能出现在数字后面,比如”123E0“,并且后面必须跟”+“或者”-“或者数字,而且后面不能再有”.",并且最多只能出现一次。

代码:

class Solution {
public:
bool isNumber(const char *s)
{
bool has_dot = false;
bool has_e = false;
bool has_num = false;
while(*s == ' ') //前面都是空格
s++;
if(*s == '+' || *s == '-') //首位是+-
s++;
while(*s && *s != ' ') //*s是' '时也停止遍历,如"123 123","123 "
{
if((*s == 'e' || *s == 'E') && !has_e) //遇到E或者e,并且没有出现过e,就继续判断
{
if(!has_num) //e前面必须有数字,比如e12是非法的数
return false;
has_dot = has_e = true;//如果出现e,则has_dot也要置为真,因为e后面也不能有'.'
if(*(s+1) == '-' || *(s+1) == '+') //下一位可以为符号位 '+-'
{
s++;
}
if (!isdigit(*(s + 1))) //下一位或者符号位的下一位必须为数字,0也可以
return false;
}
else
{
if(*s == '.' && !has_dot) //'.'之前不能有e,有e的时候已经把has_dot置为真
{
has_dot = true;
}
else
{
if(isdigit(*s))
{
has_num = true;
}
else
return false;//如果上面情况都不满足,则返回假
}
}
s++;
}
while(*s) //判断空格后面是否还有其他字符,如果有,则非法,如"123 123"
{
if(*s == ' ')
s++;
else
return false;
}
return has_num;//如果没有数字也返回假,如'.'
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: