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,需要去掉字符串两边的空白字符。
2,数字的表达式可以是科学表达法。
对于1来说,trim函数来去掉前后空白符。
对于2 科学表达式的正则为:
String regx = "^((-?\\d+.?\\d*)[Ee]{1}(-?\\d+))$";//科学计数法正则表达式
这个网上找的表达式,不一定准确。主要是先要知道科学表达式是什么样子。
解法:
1,trim去掉空白,然后得到string length。
2,设计一个正则来判断。
尝试了多次,还是没有全pass。
难道真的要各种if来判断,这道题如果能够正确理解题意,并确切知道所有的属于有效数字的情况,然后根据条件判断应该不难。难点应该考虑全所有的case
Discuss中别人的解法:
public boolean isNumber(String s) {
char[] c=s.trim().toCharArray();
if (c.length==0) return false;
int i=0,num=0;
if (c[i]=='+'||c[i]=='-') i++;
for(;i<c.length&&(c[i]>='0'&&c[i]<='9');i++) num++;
if (i<c.length&&c[i]=='.')i++;
for(;i<c.length&&(c[i]>='0'&&c[i]<='9');i++) num++;
if (num==0) return false;
if (i==c.length) return true;
else if (i<c.length&&c[i]!='e') return false;
else i++;
num=0;
if (i<c.length&&(c[i]=='+'||c[i]=='-')) i++;
for(;i<c.length&&(c[i]>='0'&&c[i]<='9');i++) num++;
if (num==0) return false;
if (i==c.length) return true;
else return false;
}