您的位置:首页 > 其它

Leetcode: Valid Number

2014-02-01 10:29 435 查看
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) {
if (s == NULL || *s == 0) {
return false;
}

while (*s != 0) {
if (*s == ' ') {
++s;
}
else {
break;
}
}
if (*s == '+' || *s == '-') {
++s;
}
if (*s == 0) {
return false;
}

bool digit = false;
bool epow = false;
bool dot = false;
while (*s != 0) {
if (*s < '0' || *s > '9') {
if (*s == '.') {
if (dot) {
return false;
}
dot = true;
if (epow) {
return false;
}
}
else if (!digit) {
return false;
}
else if (*s == 'e') {
if (epow) {
return false;
}
epow = true;
digit = false;
if (*(s+1) == '+' || *(s+1) == '-') {
++s;
}
}
else if (*s == ' ') {
++s;
while (*s != 0 && *s == ' ') {
++s;
}
return (*s == 0);
}
else {
return false;
}
}
else {
digit = true;
}
++s;
}

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