65. Valid Number

来源:互联网 发布:禅道 mysql数据库连接 编辑:程序博客网 时间:2024/06/07 00:46

Validate if a given string is numeric.

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

"2e10" => true



<span style="font-size:14px;">public class Solution {    public boolean isNumber(String s) {        s=s.trim();        boolean res;        int n=s.length();        if(n==0)            return false;        //数字,小数点,e,数        boolean hasDigit=false,hasDot=false,hasE=false,hasS=false;        char temp;        for(int i=0;i<n;i++){            temp=s.charAt(i);            if(temp>='0'&&temp<='9'){                hasDigit=hasS=true;                continue;            }            switch(temp){                case '+':                case '-':                    if(hasS)                        return false;                    hasS=true;                    continue;                case '.':                    if(hasDot)                        return false;                    hasDot=hasS=true;                    continue;                case 'e':                    if(!hasDigit||hasE)//have e or no digit                        return false;                    hasDigit=false;                    hasE=true;                    hasS=false;                    hasDot=true;//e后面的都是整数                    continue;                default:                    return false;            }                        }                return hasDigit;    }   }</span>


0 0
原创粉丝点击