题目描述
验证给定的字符串是否为数字。
例如:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10” => true
说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。
思路:
主要是考虑各种可能的情况,如”+.” ” 123” 等等。
代码
class Solution {
public boolean isNumber(String s) {
boolean ret = false;
if(s == null || s.equals("")){
return ret;
}
if("+.".equals(s.trim())) return false;
if("-.".equals(s.trim())) return false;
char[] str2char = s.toCharArray();
int start = 0;
for(int i = 0; i < str2char.length;++i){
if(str2char[i] == ' ') {
start ++;
continue;
}
break;
}
int end = str2char.length;
for(int i = str2char.length -1 ; i >=0 ;-- i){
if(str2char[i] == ' ') {
end --;
continue;
}
break;
}
if(start == str2char.length) return ret;
int countE = 0;
int countDot = 0;
boolean hasE = false;
boolean hasDot = false;
int countP = 0;
int countC = 0;
int posE = 0;
int posDot = 0;
int posC = 0;
int posP = 0;
for(int i = start; i < end; ++ i){
if(i == start && (str2char[i] > '9' || str2char[i] < '0') && str2char[i] != '-' && str2char[i] != '+' && str2char[i] != '.')
return ret;
if(i == start && (str2char[i] == '-' || str2char[i] == '+')){
continue;
}
if((str2char[i] <= '9' && str2char[i] >= '0') || str2char[i] == 'e' || str2char[i] == 'E' || str2char[i] =='.' ||
str2char[i] =='+' || str2char[i] == '-'){
if(countE <= 1 && countDot <= 1 && str2char[i] <= '9' && str2char[i] >= '0'){
continue;
}
if(str2char[i] == 'e' || str2char[i] == 'E'){
hasE = true;
countE ++;
posE = i;
continue;
}
if(str2char[i] == '.'){
hasDot = true;
posDot = i;
countDot ++;
continue;
}
if(str2char[i] == '+'){
countP ++;
posP = i;
continue;
}
if(str2char[i] == '-'){
countC ++;
posC = i;
continue;
}
}
if(str2char[i] > '9' || str2char[i] < '0' ){
return ret;
}
}
if(countE > 1)
return ret;
if(countDot > 1)
return ret;
if(countP > 1){
return ret;
}
if(countC > 1){
return ret;
}
if((countP == 1 || countC == 1) && !hasE ) return ret;
if(countP == 1 && posP == end - 1) return ret;
if(countC == 1 && posC == end - 1) return ret;
if(countP == 1 && hasE && posE == posP - 1 && posP != end - 1) return true;
if(countC == 1 && hasE && posE == posC - 1 && posC != end - 1) return true;
if(hasE && hasDot && posE < posDot) return ret;
if(hasE && (posE == end - 1 || str2char[posE + 1] > '9' || str2char[posE + 1] < '0' ||
(hasDot && posDot==start && posE == posDot + 1) ||
(posE-1 < start || str2char[posE - 1] == '+' || str2char[posE - 1] =='-') ))
return ret;
if(hasDot && ((posDot -1) >= start &&
((str2char[posDot - 1] > '9' || str2char[posDot - 1] < '0') &&
(str2char[posDot - 1] != '+' && str2char[posDot - 1] != '-') ))) return ret;
if(end - start == 1 && hasDot) return ret;
return true;
}
}