题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
解法一:根据题意一点点来
思路: 自己憋出来的,很不优雅
public class Solution {
public boolean isNumeric(char[] str) {
if(str==null||str.length==0) return false;
boolean hasnumber = false;
boolean hasdecimal = false;
for(int i=((str[0]=='+'||str[0]=='-')?1:0);i<str.length;i++){
char c = str[i];
if(c=='.'){
if(hasdecimal==true) return false;
hasdecimal = true;
}else if(c=='e'||c=='E'){
if(hasnumber==false) return false;
return isNumbericAfterE(str,i+1,str.length-1);
}else if(c>='0'&&c<='9'){
hasnumber = true;
}else return false;
}
return true;
}
//e后
private boolean isNumbericAfterE(char[] str,int i,int j){
if(i>j) return false;
for(int t=((str[i]=='+'||str[i]=='-')?i+1:i);t<=j;t++){
char c = str[t];
if(c>='0'&&c<='9'){
continue;
}else
return false;
}
return true;
}
}
解法二:骚操作
public class Solution {
public boolean isNumeric(char[] str) {
if(str==null||str.length==0) return false;
try{
double result = Double.parseDouble(new String(str));
return true;
}catch(Exception e){
return false;
}
}
}
解法三:正则表达式
思路: [+ -]?\d*(.\d+)?([eE][+ -]?\d+)? java中需要对特殊字符转义±《》等
public class Solution {
public boolean isNumeric(char[] str) {
String string = String.valueOf(str);
return string.matches("[\\+\\-]?\\d*(\\.\\d+)?([eE][\\+\\-]?\\d+)?");
}
}
解法三:真他妈的漂亮
public class Solution {
int index = 0;
public boolean isNumeric(char[] str) {
if(str==null||str.length==0) return false;
boolean flag = scanInteger(str);
if(index<str.length&&str[index]=='.'){
index++;
flag = unsignInteger(str)||flag;
}
if(index<str.length&&(str[index]=='e'||str[index]=='E')){
index++;
flag = flag&&scanInteger(str);
}
return flag&&index==str.length;
}
private boolean scanInteger(char[] str){
if(index<str.length&&(str[index]=='+'||str[index]=='-')) index++;
return unsignInteger(str);
}
private boolean unsignInteger(char[] str){
int start = index;
while(index<str.length&&(str[index]>='0'&&str[index]<='9')) index++;
return start<index;
}
}