首页 > 代码库 > Valid Number

Valid Number

题目

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

方法

分以下几个步骤: 
1. 将字符串的最前面和最后面的空格去掉。
2. 判断是否有e,并根据有e的情况进行判断:e前面是浮点,e后面必须是整形。
3. 没有e,则判断整个字符串是不是浮点。注意字符串前面的正负号别忘了。
PS:可以将使用小数点和e将字符串划分成3部分,进行判断,只需要遍历一遍字符串。
可以参考:http://blog.csdn.net/sunbaigui/article/details/8981356
    private boolean isDouble(String s) {
    	if (s.charAt(0) == '-' || s.charAt(0) == '+') {
    		if (s.length() == 1) {
    			return false;
    		} else {
    			s = s.substring(1);
    		}
    	}
        int len = s.length();
        boolean hasPoint = false;
        boolean pointNext = false;
        boolean pointPre = false;
        for(int i = 0; i < len; i++) {
            char cur = s.charAt(i);
            if (cur == '.') {
                if (hasPoint) {
                    return false;
                } else {
                    hasPoint = true;
                }
            } else if (cur>= '0' && cur <= '9') {
                if (hasPoint) {
                    pointNext = true;
                } else {
                    pointPre = true;
                }
            } else {
                return false;
            }
        }
        if (hasPoint && (pointNext == false && pointPre == false)) {
            return false;
        } else {
            return true;
        }
    }
    
    
    private boolean isInteger(String s) {
    	if (s.charAt(0) == '-' || s.charAt(0) == '+') {
    		if (s.length() == 1) {
    			return false;
    		} else {
    			s = s.substring(1);
    		}
    	}
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char cur = s.charAt(i);
            if (!(cur>= '0' && cur <= '9')) {
                return false;
            }
        }
        return true;
    }
    
    
    public boolean isNumber(String s) {
        if (s == null || s.length() == 0) {
            return false;
        } 
        
        //
        while(!s.equals("") && s.charAt(0) == ' ') {
            s = s.substring(1);
        }
        while(!s.equals("") && s.charAt(s.length() - 1) == ' ') {
            s = s.substring(0, s.length() - 1);
        }
        if (s.equals("")) {
            return false;
        }
        
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char cur = s.charAt(i);
            if (cur == 'e') {
                if ((i == 0 || i == len - 1)) {
                    return false;
                } else {
                     return isDouble(s.substring(0, i)) && isInteger(s.substring(i + 1));
                }
            } 
        }
        return isDouble(s);
    }