LeetCode OJ:Valid Number

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

基本上是leetCode上通过率最低的一道了,自己写了很多遍,就是有小问题通不过,最后参考了别人的写法,很精简,代码如下所示:

 3     bool isNumber(const char * s)
 4     {
 5         int i = 0;
 6         int digitCount = 0;
 7         while(s[i] == ' ') i++; //skip spaces
 8         
 9         if(s[i]=='+' || s[i] == '-') i++; //skip sign
10         
11         while(isdigit(s[i])){
12             digitCount++;
13             i++;
14         }
15         
16         if(s[i] == '.') i++;
17         
18         while(isdigit(s[i])){
19             digitCount++;
20             i++;
21         }
22         
23         if(digitCount==0) return false;
24     
25         if(s[i] == 'e' || s[i] == 'E'){
26             i++;
27             
28             if(s[i] == '+' || s[i] == '-') i++;//skp sign of expo
29             
30             if(!isdigit(s[i])) return false;
31             
32             while(isdigit(s[i])) i++;
33         }
34         
35         while(s[i] == ' ') i++;
36         
37         return s[i] == '';
38     }

 这题比较特殊,使用c语言做是比较方便的,因为c字符串最后一位是'',即是前面通过 i 访问到最后一位的时候也能正常运行,但是使用java的话用上面的方法如果不注意就会出现outOfBound,c++却可以,也就是说c++字符串末尾的最后一位实际上也是可以访问的。

原文地址:https://www.cnblogs.com/-wang-cheng/p/5566114.html