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

Valid Number

时间:2015-05-07 23:56:23      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:

  就是坑多一些,仔细的观察每一个case就可以了

我的代码:

技术分享
public class Solution {
    public boolean isNumber(String s)
    {
        if(s==null || s.length()==0) return false;
        s = s.trim();
        if(s.contains("e") || s.contains("E"))
        {
            int count = count(s, ‘e‘);
            if(count != 1) return false;
            String[] strs = s.split("e|E");
            if(strs.length != 2)    return false;
            return (isValidDecimal(strs[0]) || isValidNumber(strs[0]))&& isValidNumber(strs[1]);
        }
        else if(s.contains("."))
        {
            return isValidDecimal(s);
        }
        else 
        {
            return isValidNumber(s);
        }
    }
    public boolean isValidDecimal(String s)
    {
        if(s==null || s.length()==0)    return false;
        int count = count(s, ‘.‘);
        if(count != 1) return false;
        if(s.charAt(0)==‘+‘ || s.charAt(0)==‘-‘) s = s.substring(1);
        String[] strs = s.split("\\.");
        if(strs.length>2 || strs.length==0)    return false;
        if(strs.length == 1) return ispureValidNumber(strs[0]);
        if(strs[0].length() == 0 && strs[1].length()==0)    return false;
        return (ispureValidNumber(strs[0]) || strs[0].length()==0) && (ispureValidNumber(strs[1]) || strs[1].length()==0);
    }
    public boolean ispureValidNumber(String s)
    {
        if(s==null || s.length()==0)    return false;
        for(int i=0; i<s.length(); i++)
        {
            if(!charisNumber(s.charAt(i))) return false;
        }
        return true;
    }
    public boolean isValidNumber(String s)
    {
        if(s==null || s.length()==0)    return false;
        if(s.charAt(0)==‘+‘ || s.charAt(0)==‘-‘) s = s.substring(1);
        return ispureValidNumber(s);
    }
    public int count(String s, char c)
    {
        int count = 0;
        for(int i=0; i<s.length(); i++)
        {
            if(s.charAt(i) == c) count++;
        }
        return count;
    }
    public boolean charisNumber(char c)
    {
        return (c>=‘0‘ && c<=‘9‘)?true:false;
    }
}
View Code

学习之处:

  陷阱多一些~

Valid Number

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4486382.html

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