LeetCode: Valid Number 解题报告

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.

SOLUTION 1:

我们设置3个FLAG:

1. num

2. exp

3. dot

有以下情况:

(1). 出现了e,则前面要有digit,不能有e. 并且后面要有digit.

  (2). 出现了.  那么是一个小数,那么前面不可以有.和e

  (3). 出现了+, - 那么它必须是第一个,或者前一个是e,比如" 005047e+6"

实际的代码实现如下,相当的简洁。

感谢答案的提供者:http://www.ninechapter.com/solutions/valid-number/

大神哇哇哇!

 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 " => true
14         "abc" => false
15         "1 a" => false
16         "2e10" => true
17         */
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

请至主页君的GitHUB: https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/IsNumber.java

 

用正则其实也可以哦:

推荐一些较好的教程:

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

主页君就不写了,因为觉得正则实在是写不出来在面试时,真的太复杂了。

给个大神写好的正则的解答:

http://blog.csdn.net/fightforyourdream/article/details/12900751?reload

posted on 2014-10-29 19:29  Yu's Garden  阅读(1125)  评论(0编辑  收藏  举报

导航