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 shoshould gather all requirements up front before implementing one.
Solution 1:
We set three flags:
1. Num
2. Exp
3. Dot
There are the following situations:
(1). If e appears, there must be digit first, and there must be no E. There must be digit later.
(2). If it appears, it is a decimal number, so there cannot be. And E
(3). If + appears,-it must be the first, or the previous one is E, for example, "005047e + 6"
The actual code implementation is as follows, which is quite concise.
Thanks to the answer provider: http://www.ninechapter.com/solutions/valid-number/
Wow!
1 public class Solution { 2 public boolean isNumber(String s) { 3 if (s == null) { 4 return false; 5 } 6 7 // cut the leading spaces and tail spaces. 8 String sCut = s.trim(); 9 10 /*11 Some examples:12 "0" => true 13 " 0.1 " => true14 "abc" => false15 "1 a" => false16 "2e10" => true17 */18 19 int len = sCut.length();20 21 boolean num = false;22 boolean exp = false;23 boolean dot = false;24 25 for (int i = 0; i < len; i++) {26 char c = sCut.charAt(i);27 if (c == ‘e‘) {28 if (!num || exp) {29 return false;30 }31 exp = true;32 num = false; // Should be: 2e2 , so there should be number follow "e"33 } else if (c <= ‘9‘ && c >= ‘0‘) {34 num = true;35 } else if (c == ‘.‘) {36 if (exp || dot) { // can‘t be: e0.2 can‘t be: ..37 return false;38 }39 dot = true;40 } else if (c == ‘+‘ || c == ‘-‘) {41 if (i != 0 && sCut.charAt(i - 1) != ‘e‘) { // filter : " 005047e+6", this is true.42 return false;43 }44 } else {45 // invalid character.46 return false;47 }48 }49 50 return num;51 }52 }
View code
Please go to the home page of Jun GitHub: https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/IsNumber.java
You can also use regular expressions:
Recommended Tutorials:
Http://developer.51cto.com/art/200912/166310.htm
Http://luolei.org/2013/09/regula-expression-simple-tutorial/
Http://net.tutsplus.com/tutorials/php/regular-expressions-for-dummies-screencast-series/
Http://deerchao.net/tutorials/regex/regex.htm
The homepage is not written, because it is too complicated to write regular expressions during the interview.
Answers to the regular expressions written by a great God:
Http://blog.csdn.net/fightforyourdream/article/details/12900751? Reload
Leetcode: valid number solution report