您的位置:首页 > 其它

LeetCode Valid Number(判断字符串是否是合法的数字表示 )

2016-07-25 11:49 676 查看
思路:

1、如果是指数表现法,e后不能有小数

2、数字中有带有正负表示只能有一个

3、小数时点只能有一个

代码如下:

public class Solution
{
public boolean isNumber(String s) {
s = s.trim();
int len = s.length();
if (0 == len) return false;

boolean hasE = false, hasDot = false, hasDigit = false, hasFirst = false;

for (int i = 0; i < len; i++)
{
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
hasFirst = hasDigit = true;
continue;
}

switch (c) {
case 'e':
if (hasE || !hasDigit) return false;
hasE = true;

hasDot = true;
hasFirst = hasDigit = false;
break;
case '.':
if (hasDot) return false;
hasDot = true;
hasFirst = true;
break;
case '+':
case '-':
if (hasFirst) return false;
hasFirst = true;
break;
default:
return false;
}
}

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