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.

 1 public class Solution {
 2     public boolean isNumber(String s) {
 3         boolean result = true;
 4         s = s.trim();//去掉前面和后面的空格
 5         if(0 != s.length() && (s.charAt(0) == '+' || s.charAt(0) == '-'))
 6             s = s.substring(1, s.length());
 7         if(0 == s.length())
 8             return false;
 9         boolean flag_point = false;
10         boolean flag_e = false;//记录小数点和字母e
11         
12         
13         for(int i = 0; i < s.length(); i++){
14             char ch = s.charAt(i);//第i个字符
15             if('.' == ch){                
16                 if(flag_e || flag_point || !((i + 1 < s.length() && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9')||
17                     (i - 1 >= 0 && s.charAt(i - 1) >= '0' && s.charAt(i - 1) <= '9'))//e出现过就不能出现小数点了
18                     )
19                 {
20                     return false;
21                 }
22                 flag_point = true;
23             }//小数点后面或者前面有数字即可
24             if('e' == ch){                                    
25                 if(flag_e || 
26                         !((i + 1 < s.length() && (s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9' || s.charAt(i + 1) == '+'|| s.charAt(i + 1) == '-'))&&
27                                 (i - 1 >= 0 && (s.charAt(i - 1) >= '0' && s.charAt(i - 1) <= '9' || s.charAt(i - 1) == '.'))))
28                 {
29                     return false;
30                 }
31                 flag_e = true;
32             }//小数点和e的个数
33             if(flag_e && (ch == '+' || ch == '-')){
34                 if(!(s.charAt(i - 1) == 'e') ||
35                         !(i + 1 < s.length() && (s.charAt(i + 1)>= '0' && s.charAt(i + 1) <= '9')))
36                     return false;
37             }//+ 出现过e
38             else if(!((ch >= '0' && ch <= '9') || ch == '.' || ch == 'e')){
39                 return false;
40             }
41         }
42         
43         return result;
44     }
45 }

还是要先看一下哪一些是合理的,可以先百度一下。在实现,要不然后面要针对测试用例一个个修改,严重拉低通过率

posted on 2014-11-16 11:53  luckygxf  阅读(179)  评论(0编辑  收藏  举报

导航