美文网首页
20-表示数值的字符串

20-表示数值的字符串

作者: 一方乌鸦 | 来源:发表于2020-05-05 22:00 被阅读0次

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、"5e2"、"-123"、"3.1416"、"0123"都表示数值,但"12e"、"1a3.14"、"1.2.3"、"+-5"、"-1E-16"及"12e+5.4"都不是。

class Solution {
    int index = 0;

    public boolean isNumber(String s) {
        if (s == null) return false;
        s = s.trim();
        if (s.length() == 0) return false;
        
        char[] a = s.toCharArray();
        boolean numeric = integer(a);
        if (inRange(a.length) &&  a[index] == '.')  {
            index++;
            numeric = uInteger(a) || numeric;
        }
        if (inRange(a.length)  && (a[index] == 'e' || a[index] == 'E')) {
            index++;
            numeric = numeric && integer(a);
        }
        return numeric && index == a.length;
    }

    private boolean uInteger(char[] a) {
        int originIndex = index;
        while(index < a.length && a[index] >= '0' && a[index] <= '9') index++;
        return index > originIndex;
    }

    private boolean integer(char[] a) {
        if (index >= a.length) return false;
        if (a[index] == '-' || a[index] == '+') index++;
        return uInteger(a);
    }

    private boolean inRange(int length) {
        return index < length;
    }
}

相关文章

网友评论

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

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