标签:
Valid Number
问题:
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.
思路:
就是坑多一些,仔细的观察每一个case就可以了
我的代码:
public class Solution { public boolean isNumber(String s) { if(s==null || s.length()==0) return false; s = s.trim(); if(s.contains("e") || s.contains("E")) { int count = count(s, ‘e‘); if(count != 1) return false; String[] strs = s.split("e|E"); if(strs.length != 2) return false; return (isValidDecimal(strs[0]) || isValidNumber(strs[0]))&& isValidNumber(strs[1]); } else if(s.contains(".")) { return isValidDecimal(s); } else { return isValidNumber(s); } } public boolean isValidDecimal(String s) { if(s==null || s.length()==0) return false; int count = count(s, ‘.‘); if(count != 1) return false; if(s.charAt(0)==‘+‘ || s.charAt(0)==‘-‘) s = s.substring(1); String[] strs = s.split("\\."); if(strs.length>2 || strs.length==0) return false; if(strs.length == 1) return ispureValidNumber(strs[0]); if(strs[0].length() == 0 && strs[1].length()==0) return false; return (ispureValidNumber(strs[0]) || strs[0].length()==0) && (ispureValidNumber(strs[1]) || strs[1].length()==0); } public boolean ispureValidNumber(String s) { if(s==null || s.length()==0) return false; for(int i=0; i<s.length(); i++) { if(!charisNumber(s.charAt(i))) return false; } return true; } public boolean isValidNumber(String s) { if(s==null || s.length()==0) return false; if(s.charAt(0)==‘+‘ || s.charAt(0)==‘-‘) s = s.substring(1); return ispureValidNumber(s); } public int count(String s, char c) { int count = 0; for(int i=0; i<s.length(); i++) { if(s.charAt(i) == c) count++; } return count; } public boolean charisNumber(char c) { return (c>=‘0‘ && c<=‘9‘)?true:false; } }
学习之处:
陷阱多一些~
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4486382.html