请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、"5e2"、"-123"、"3.1416"、"0123"都表示数值,但"12e"、"1a3.14"、"1.2.3"、"+-5"、"-1E-16"及"12e+5.4"都不是。
class Solution {
int index = 0;
public boolean isNumber(String s) {
if (s == null) return false;
s = s.trim();
if (s.length() == 0) return false;
char[] a = s.toCharArray();
boolean numeric = integer(a);
if (inRange(a.length) && a[index] == '.') {
index++;
numeric = uInteger(a) || numeric;
}
if (inRange(a.length) && (a[index] == 'e' || a[index] == 'E')) {
index++;
numeric = numeric && integer(a);
}
return numeric && index == a.length;
}
private boolean uInteger(char[] a) {
int originIndex = index;
while(index < a.length && a[index] >= '0' && a[index] <= '9') index++;
return index > originIndex;
}
private boolean integer(char[] a) {
if (index >= a.length) return false;
if (a[index] == '-' || a[index] == '+') index++;
return uInteger(a);
}
private boolean inRange(int length) {
return index < length;
}
}
网友评论