码迷,mamicode.com
首页 > 其他好文 > 详细

65. Valid Number

时间:2016-09-04 06:53:41      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

public boolean isNumber(String s) {
    s = s.trim();
    
    boolean pointSeen = false;
    boolean eSeen = false;
    boolean numberSeen = false;
    boolean numberAfterE = true;
    for(int i=0; i<s.length(); i++) {
        if(‘0‘ <= s.charAt(i) && s.charAt(i) <= ‘9‘) {
            numberSeen = true;
            numberAfterE = true;
        } else if(s.charAt(i) == ‘.‘) {
            if(eSeen || pointSeen) {
                return false;
            }
            pointSeen = true;
        } else if(s.charAt(i) == ‘e‘) {
            if(eSeen || !numberSeen) {
                return false;
            }
            numberAfterE = false;
            eSeen = true;
        } else if(s.charAt(i) == ‘-‘ || s.charAt(i) == ‘+‘) {
            if(i != 0 && s.charAt(i-1) != ‘e‘) {
                return false;
            }
        } else {
            return false;
        }
    }
    
    return numberSeen && numberAfterE;
}

We start with trimming.

    If we see [0-9] we reset the number flags.
    We can only see . if we didn‘t see e or ..
    We can only see e if we didn‘t see e but we did see a number. We reset numberAfterE flag.
    We can only see + and - in the beginning and after an e
    any other character break the validation.

At the and it is only valid if there was at least 1 number and if we did see an e then a number after it as well.

 

65. Valid Number

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5838521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!