字符串:表示数值的字符串
时间限制:1秒 空间限制:32768K
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,“5e2”,”-123”,“3.1416”和”-1E-16”都表示数值。 但是”12e”,“1a3.14”,“1.2.3”,”±5”和”12e+4.3”都不是。
用例
“-.123”
代码
public class Solution {
public boolean isNumeric(char[] str) {
if(str.length==0){
return false;
}
boolean first=true;
boolean hasE=false;
boolean hasPoint= false;
for(int i=0;i<str.length;i++){
if(str[i]=='E'||str[i]=='e'){
if(hasE||first||str[i-1]=='.'||str[i-1]=='+'||str[i-1]=='-')
return false;
if(i==str.length-1)
return false;
hasE=true;
}else if(str[i]=='.'){
if(first||hasE||hasPoint)
return false;
hasPoint=true;
}else if(str[i]=='+'||str[i]=='-'){
if(!first){
if(i==str.length-1)
return false;
if(str[i-1]!='E'&&str[i-1]!='e'){
return false;
}
}
}else if(str[i]<'0'||str[i]>'9'){
return false;
}
first=false;
}
return true;
}
}
还没有评论,来说两句吧...