美文网首页
面试题20:表示数值的字符串

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

作者: scott_alpha | 来源:发表于2019-10-07 00:03 被阅读0次

    题目:请实现一个函数用于判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100“、”5e2“都表示数值,但”12e“、”1a3.14“都不是
    思路:数字的基本格式为:(A.B E/e A) ,按顺序进行判断。A代表带符号整数,B代表不带符号整数。
    解决方案:

    public class Question20 {
        public static boolean isNumber(char[] str){
            if (str == null) return false;
            int[] index = new int[1];
            // 用于记录当前字符位置
            index[0] = 0;
            boolean isNumeric = isInteger(str, index);
            if (index[0] < str.length && str[index[0]] == '.'){
                index[0] ++;
                isNumeric = isUnsignedInteger(str, index) || isNumeric;
            }
            if (index[0] < str.length && (str[index[0]] == 'e' || str[index[0]] == 'E')){
                index[0]++;
                isNumeric = isInteger(str, index) && isNumeric;
            }
            if (isNumeric && index[0] == str.length){
                return true;
            }else {
                return false;
            }
    
        }
        private static boolean isInteger(char[] str, int[] index){
            if (index[0] < str.length &&(str[index[0]] == '+' || str[index[0]] == '-'))
                index[0]++;
            return isUnsignedInteger(str, index);
        }
        private static boolean isUnsignedInteger(char[] str, int[] index){
            int start = index[0];
            while (index[0] <str.length && (str[index[0]]<='9') && (str[index[0]]>='0')){
                index[0]++;
            }
           if (index[0] > start){
                return true;
           }else{
                return false;
           }
        }
    
        public static void main(String[] args) {
            char[] str = new char[]{'+','1','0','0'};
            System.out.println(isNumber(str));
        }
    }
    

    [https://www.cnblogs.com/yongh/p/9765589.html]

    相关文章

      网友评论

          本文标题:面试题20:表示数值的字符串

          本文链接:https://www.haomeiwen.com/subject/equppctx.html