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.前边不能出现过小数点或者exp 2.不能单独存在(.) 3.如果他是0位 后边必须是数字 4. 如果是最后一位前边也必须是数字
对于 e 或者E
1. 不能前边存在exp 2. 不能是最后一位或者第一位 3.前一位必须是数字或者'.' 4. 后一位必须是数字或者加减号
对于加减号:
1.不能是最后一位 2. 如果不是第一位的话能把么前边必须是e 或者E 3.下一位必须是数字或者'.'
public class Solution {
public boolean isNumber(String s) {
if (s == null) {
return false;
}
s = s.trim();
if (s.length() == 0) {
return false;
}
boolean dot = false;
boolean exp = false;
for (int i = 0; i < s.length(); i++) {
switch(s.charAt(i)) {
case '.':
if ( dot|| exp|| ((i==0||!(s.charAt(i-1)>='0'&&s.charAt(i-1)<='9'))
&& (i==s.length()-1||!(s.charAt(i+1)>='0'&&s.charAt(i+1)<='9')))){
return false;
}
dot = true;
break;
case 'e':
case 'E':
if (i == 0 || i == s. length() - 1|| exp|| !((s.charAt(i - 1) >= '0' && s.charAt(i - 1) <= '9')|| s.charAt(i - 1) == '.')|| !((s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') || s.charAt(i + 1) == '+' || s.charAt(i + 1) == '-' )) {
return false;
}
exp = true;
break;
case '+':
case '-':
if ((i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E') || i == s.length() - 1 || !((s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') || s.charAt(i + 1) == '.')) {
return false;
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
default://对于其他情况 如字母空格
return false;
}
}
return true;
}
}
没有评论:
发表评论