您的位置:首页 > 其它

LeetCode | Valid Number

2014-08-21 20:45 218 查看
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.

题目解析:

判断一个字符串中的数据是否合法。要考虑很多种情况,不仅要考虑正负号,还要考虑e后面的数字,紧跟e后面还可能有正负号。详见代码,需要好好研究研究。

class Solution {
public:
bool isNumber(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s == NULL)
return false;

while(isspace(*s))  //跳过前面的空格
s++;

if (*s == '+' || *s == '-')
s++;

bool eAppear = false;   //是否出现了e
bool dotAppear = false; //是否出现了.
bool firstPart = false; //在e的前面一段数字
bool secondPart = false;//e的后面一段数字
bool spaceAppear = false;   //是否数据中间出现了空格
while(*s != '\0')
{
if (*s == '.')
{   //如果已经有 '.' 或者已经有e 或者已经有空格了
if (dotAppear || eAppear || spaceAppear)
return false;
else
dotAppear = true;
}
else if (*s == 'e' || *s == 'E')
{   //如果已经有e,或者已经在第二段数据当中 或者已经有空格了
if (eAppear || !firstPart || spaceAppear)
return false;
else
eAppear = true;
}
else if (isdigit(*s))
{
if (spaceAppear)
return false;

if (!eAppear)
firstPart = true;
else
secondPart = true;
}
else if (*s == '+' || *s == '-')
{   //如果已经有空格出现
if (spaceAppear)
return false;
//这个是出现在e后面的正负号
if (!eAppear || !(*(s-1) == 'e' || *(s-1) == 'E'))
return false;
}   //如果是空格,则置位
else if (isspace(*s))
spaceAppear = true;
else
return false;   //其他字符

s++;
}
//没有碰到数字
if (!firstPart)
return false;
else if (eAppear && !secondPart)    //e出现了,但e后面没有数字
return false;
else
return true;
}
};


方案二:

可以写一个正则表达式……不会写,贴上来图个乐子吧^_^

public class ValidNumber {
public boolean isNumber(String s) {
return s.trim().matches("[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?");
}
}


这是我见过最简洁的代码,一行一道题……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: