表示数值的字符串

题目:

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、"5e2"、"-123"、"3.1416"、"-1E-16"都表示数值,但是"12e"、"1a3.14"、"1.2.3"、"+-5"、"12e+5.4"都不是。

 

解答:

 

 1 public class Solution {
 2     
 3     private int index = 0;
 4   
 5     public boolean isNumeric(char[] str) {
 6         if(str == null || str.length == 0) {
 7             return false;
 8         }
 9          
10         boolean flag = scanInteger(str);
11          
12         if (index < str.length && str[index] == '.') {
13             index++;
14             flag = scanUnsignedInteger(str) || flag;
15         }
16          
17         if (index < str.length && (str[index] == 'E' || str[index] == 'e')) {
18             index++;
19             flag = flag && scanInteger(str);
20         }
21          
22         return flag && index == str.length;
23          
24     }
25      
26     private boolean scanInteger(char[] str) {
27         if (index < str.length && (str[index] == '+' || str[index] == '-') )
28             index++;
29         return scanUnsignedInteger(str);
30          
31     }
32      
33     private boolean scanUnsignedInteger(char[] str) {
34         int start = index;
35         while (index < str.length && str[index] >= '0' && str[index] <= '9')
36             index++;
37         return start < index; //是否存在整数
38     }
39 }

 

posted @ 2019-03-05 09:58  林木声  阅读(136)  评论(0编辑  收藏  举报