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.
Analysis:
The key point is to clarify which case is valid. I used a recursive method with several control switches. With such method, it is easy for us to definite different rules of feasibility.
Solution:
1 public class Solution { 2 public boolean isNumber(String s) { 3 s = s.trim(); 4 //check whether there is 'e'. 5 int index = s.indexOf("e"); 6 7 if (index!=-1){ 8 String left = s.substring(0,index); 9 String right = s.substring(index+1,s.length()); 10 if (isNumberRecur(left,true,true,true,false)&&isNumberRecur(right,false,true,true,false)) 11 return true; 12 else return false; 13 } else 14 if (isNumberRecur(s,true,true,true,false)) return true; 15 else return false; 16 17 } 18 19 public boolean isNumberRecur(String s, boolean canBeDouble, boolean canHaveSymbol, boolean canZeroHead, boolean canBeNull){ 20 if (!canBeNull && s.isEmpty()) return false; 21 if (canBeNull && s.isEmpty()) return true; 22 int index; 23 24 //NOTE: check symbol before checking float! 25 //check positive symbol 26 index = s.indexOf("+"); 27 if (index!=-1 && !canHaveSymbol) return false; 28 if (canHaveSymbol && index!=-1 && index!=0) return false; 29 if (canHaveSymbol && index==0) 30 return isNumberRecur(s.substring(1,s.length()),true,false,true,false); 31 32 //check negative symbol 33 index = s.indexOf("-"); 34 if (index!=-1 && !canHaveSymbol) return false; 35 if (canHaveSymbol && index!=-1 && index!=0) return false; 36 if (canHaveSymbol && index==0) 37 return isNumberRecur(s.substring(1,s.length()),true,false,true,false); 38 39 index = s.indexOf("."); 40 if (canBeDouble && index!=-1){ 41 String left = s.substring(0,index); 42 String right = s.substring(index+1,s.length()); 43 44 //NOTE: this code is only for the case "3." to be true in leetcode while "." is invalid. 45 if (left.isEmpty() && right.isEmpty()) return false; 46 if (isNumberRecur(left,false,true,true,true) && isNumberRecur(right,false,false,true,true)) 47 return true; 48 else return false; 49 } 50 51 if (!canBeDouble && index!=-1) return false; 52 53 //check zero head. 54 if (!canZeroHead && s.charAt(0)=='0' && s.length()>1) return false; 55 56 //check whether all chars are numbers. 57 for (int i=0;i<s.length();i++) 58 if (s.charAt(i)<'0' || s.charAt(i)>'9') return false; 59 60 return true; 61 } 62 63 }