判断给出的字符串是否是数字
一些例子:
"0"=>true
" 0.1 "=>true
"abc"=>false
"1 b"=>false
"3e10"=>true
" 0.1 "=>true
"abc"=>false
"1 b"=>false
"3e10"=>true
public class Solution { public boolean isNumber(String s) { if(s.matches(".*[a-zA-Z]$")) return false; try{ double s1 = Double.parseDouble(s); return true; }catch(Exception e){ return false; } } }
// 亲测本机上没问题,提交却显示错误,难道是因为我用的是Java8? public class Solution { public boolean isNumber(String s) { if (s.charAt(s.length()-1) > '9' || s.charAt(s.length()-1) < '0') return false; try { Double.valueOf(s); } catch (Exception e) { return false; } return true; } }
All we need is to have a couple of flags so we can process the string in linear time:
public boolean isNumber(String s) { s = s.trim(); boolean pointSeen = false; boolean eSeen = false; boolean numberSeen = false; boolean numberAfterE = true; for(int i=0; i<s.length(); i++) { if('0' <= s.charAt(i) && s.charAt(i) <= '9') { numberSeen = true; numberAfterE = true; } else if(s.charAt(i) == '.') { if(eSeen || pointSeen) { return false; } pointSeen = true; } else if(s.charAt(i) == 'e') { if(eSeen || !numberSeen) { return false; } numberAfterE = false; eSeen = true; } else if(s.charAt(i) == '-' || s.charAt(i) == '+') { if(i != 0 && s.charAt(i-1) != 'e') { return false; } } else { return false; } } return numberSeen && numberAfterE; }
We start with trimming.
At the and it is only valid if there was at least 1 number and if we did see an e then a number after it as well.
So basically the number should match this regular expression:
[-+]?(([0-9]+(.[0-9]*)?)|.[0-9]+)(e[-+]?[0-9]+)?