面试题54:表示数值的字符串

来源:互联网 发布:json 20160212.jar 编辑:程序博客网 时间:2024/06/14 01:32
public class Solution {    public boolean isNumeric(char[] str) {        if(str==null||str.length==0)            return false;        int index=0;        if(str[index]=='+'||str[index]=='-'){            index++;            if(index==str.length)                return false;        }        boolean numeric=true;                index=scanDigits(str,index);                if(index!=str.length){                        if(str[index]=='.'){//如果是浮点数                index++;                index=scanDigits(str,index);                if(index<str.length&&(str[index]=='e'||str[index]=='E')){                    numeric=isExponential(str,index);                    return numeric;                }            }else if(str[index]=='e'||str[index]=='E'){//如果是整数                numeric=isExponential(str,index);                return numeric;            }else                numeric=false;        }        return (numeric&&(index==str.length));    }                   public static int scanDigits(char[] str, int index) {        while (index != str.length && str[index] >= '0' && str[index] <= '9') {            index++;        }        return index;    }        public static boolean isExponential(char[] str,int index){         if(str[index]!='e'&&str[index]!='E')            return false;        index++;        if(index==str.length)//判断边界            return false;        if(str[index]=='+'||str[index]=='-')            index++;        if(index==str.length)            return false;        index=scanDigits(str,index);        return (index==str.length)?true:false;            }        }

原创粉丝点击