美文网首页
Valid Number

Valid Number

作者: BLUE_fdf9 | 来源:发表于2018-08-22 22:49 被阅读0次

题目
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.

答案

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

相关文章

网友评论

      本文标题:Valid Number

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