劍指offer 面試題20:表示數值的字符串 java

題目

  • 請實現一個函數用來判斷字符串是否表示數值(包括整數和小數)。例如,字符串“+100”、“5e2”、“-123”、“3.1416”及“-1E-16”都表示數值,但“12e”、“1a3.14”、“1.2.3”、“+-5”及“12e+5.4”都不是。
public class IsNumeric {
    public static void main(String args[]) {
        String str = "2.0E1";
        System.out.println(isNumeric(str.toCharArray()));

    }

    /**
     * A.B e/E A
     * @param nums
     * @return
     */
    private static boolean isNumeric(char[] nums) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        // 記錄nums的下標值
        int[] index = new int[1];
        //  判斷A部分是否爲整數
        boolean isNumeric = isInteger(nums, index);
        //  判斷B部分
        if (index[0] < nums.length && nums[index[0]] == '.') {
            index[0]++;
            isNumeric = isUnsignedInteger(nums, index) || isNumeric;
        }
        // 判斷e/E後面的A 部分
        if (index[0] < nums.length && (nums[index[0]] == 'e' || nums[index[0]] == 'E')) {
            index[0]++;
            isNumeric = isInteger(nums, index) && isNumeric;
        }
        if (isNumeric && index[0] == nums.length) {
            return true;
        } else {
            return false;
        }

    }

    private static boolean isInteger(char[] nums, int[] index) {
        if (index[0] < nums.length && (nums[index[0]] == '+' || nums[index[0]] == '-')) {
            index[0]++;
        }
        return isUnsignedInteger(nums, index);
    }

    private static boolean isUnsignedInteger(char[] nums, int[] index) {
        int lastIndex = index[0];
        while (index[0] < nums.length && (nums[index[0]] - '0' >= 0 && nums[index[0]] - '0' <= 9)) {
            index[0]++;
        }
        return lastIndex < index[0];
    }


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章