您的位置:首页 > 其它

[leetcode] Valid Number

2015-01-24 10:43 246 查看

Valid Number

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
{
public:
bool isNumber(const char *s)
{
bool has_front_num = false, has_back_num = false, has_e = false;
int len = strlen(s);
int i = 0;

while(i < len && ' ' == s[i])
i++;

if(i == len) return false;

if(i < len && (s[i] == '+' || s[i] == '-'))
i++;

while(i < len && isdigit(s[i]))
{
i++;
has_front_num = true;
}

if(i < len && s[i] == '.')
i++;

while(i < len && isdigit(s[i]))
{
i++;
has_front_num = true;
}

if(i < len && (s[i] == 'e' || s[i] == 'E') && has_front_num)
{
i++;
has_e = true;
if(i == len) return false;
}

if(i < len && (s[i] == '+' || s[i] == '-') && has_e)
i++;

while(i < len && isdigit(s[i]) && has_e)
{
i++;
has_back_num = true;
}

while(i < len && s[i] == ' ')
i++;

if(i == len && has_e && has_back_num)
return true;
else if(i == len && !has_back_num && !has_e && has_front_num)
return true;

return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: