Validate if a given string can be interpreted as a decimal number.
Some examples:
“0” => true
" 0.1 " => true
“abc” => false
“1 a” => false
“2e10” => true
" -90e3 " => true
" 1e" => false
“e3” => false
" 6e-1" => true
" 99e2.5 " => false
“53.5e93” => true
" --6 " => false
“-+3” => false
“95a54e53” => false
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
Numbers 0-9
Exponent - “e”
Positive/negative sign - “+”/"-"
Decimal point - “.”
Of course, the context of these characters also matters in the input.
一道恶心的字符串处理题,把各种case都考虑到就行:一开始会漏掉的case: {".1" - true}, {"." - false}, {“0e” - false}, {"." - false}, {“12e34e56” - false}
public boolean isNumber(String s) {
if (s == null || s.length() == 0) return false;
s = s.trim();
if (s.length() == 0) return false;
boolean first = true;
boolean hasE = false;
for (int i = 0; i < s.length(); i++) {
int[] res = getNum(s, i);
if (res[0] == -1) return false;
if (!first && res[0] < 0) return false;
i = res[1];
if (hasE && i < s.length() && s.charAt(i) == 'e') return false;
else if (i < s.length() && s.charAt(i) != 'e') return false;
else if (i == s.length() - 1 && s.charAt(i) == 'e') return false;
else
if (i < s.length() && s.charAt(i) == 'e') hasE = true;
first = false;
}
return true;
}
//return -1: not a number; 0: number; -2: with dot
public int[] getNum(String s, int i) {
int[] res = new int[]{-1, 0};
boolean dot = false;
int index = i;
boolean hasNum = false;
while (index < s.length()) {
char c = s.charAt(index);
if (!Character.isDigit(c)) {
if (index == i) {
if (c != '+' && c != '-' && c != '.') return res;
if (c == '.') dot = true;
} else {
if (hasNum && c == 'e') break;
else if(!dot && c == '.') dot = true;
else return res;
}
} else {
hasNum = true;
}
index++;
}
if (!hasNum) return res;
res[0] = 0;
if (dot) res[0] = -2;
res[1] = index;
return res;
}