第28题 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.


Solution in Java:

public class Solution {
    public boolean isNumber(String s) {
        String sTrim = s.trim();
        if(sTrim.length()==0) return false;
        if(sTrim.contains(" ")) return false;
        
        String pattern1 = "", pattern2 = "";
        if(sTrim.contains("e")){
            int indexE = sTrim.indexOf('e');
            String beforeE="", afterE="";
            if(indexE!=-1){
                beforeE = sTrim.substring(0,indexE);
                afterE = sTrim.substring(indexE+1, sTrim.length());
                indexE = sTrim.indexOf('e', indexE+1);
                if(indexE!=-1) return false;
            }
            pattern1 = "^[+,-]?[0-9]+$";
            if(!afterE.matches(pattern1)) 
                return false;
            if(beforeE.contains(".")){
                pattern1 = "^[+,-]?[0-9]*[.]{1}[0-9]+$";
                pattern2 = "^[+,-]?[0-9]+[.]{1}[0-9]*$";
                if(beforeE.matches(pattern1)||beforeE.matches(pattern2)) return true;
                else return false;
            }else{
                pattern1 = "^[+,-]?[0-9]+$";
                if(beforeE.matches(pattern1)) return true;
                else return false;
            }
        }
        else{
            if(sTrim.contains(".")){
                pattern1 = "^[+,-]?[0-9]+[.]{1}[0-9]*$";
                pattern2 = "^[+,-]?[0-9]*[.]{1}[0-9]+$";
                if(sTrim.matches(pattern1)||sTrim.matches(pattern2)) return true;
                else return false;
            }
            else{
                pattern1 = "^[+,-]?[0-9]+$";
                if(sTrim.matches(pattern1)) return true;
                else return false;
            }
    }
}



Note:

“.3”也算valid number!"3."也算valid number!但"."前后不可同时为空字符,所以要用或判断。

"7e69e"在java中用split分割,长度为2,最后不算第二个e后的空字符,所以不能检查如“e123e”格式的字符串。所以用indexOf函数查找字符"e",然后用substring获取"e"前后字符。string.indexOf('e',index)查找从string的index位置开始有无字符'e'。

  科学计数法e后可以加+或-号,后面跟数字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值