AdSense

Sunday, December 21, 2014

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.
This is a very good problem to test if you are careful, or I would like to use, meticulous, enough to consider every possible cases.

Some test cases besides the examples that trapped me:

"-1."
"."
"46.e3"
"005046e+6000"


public class ValidNumber {
    public boolean isNumber(String s) {
        if (s == null || s.length() == 0)
            return false;
        int leftBound = 0;
        int rightBound = s.length() - 1;
        while (leftBound < s.length() && s.charAt(leftBound) == ' ')
         leftBound++;
     while (rightBound > leftBound && s.charAt(rightBound) == ' ')
         rightBound--;
     while (leftBound < s.length() && (s.charAt(leftBound) == '+' || s.charAt(leftBound) == '-'))
         leftBound++;
     if (leftBound > rightBound)
         return false;
      
       
        s = s.substring(leftBound, rightBound + 1);
        boolean dot = false;
        boolean num = false;
        boolean exp = false;
        for (int i = 0; i < s.length(); i++)
        {
            if (Character.isDigit(s.charAt(i)))
                num = true;
            else if (s.charAt(i) == '.')
            {
                if (dot || exp)
                    return false;
                dot = true;
            }
            else if (s.charAt(i) == 'e')
            {
                if (exp || !num)
                    return false;
                exp = true;
                num = false;
            }
            else if ((s.charAt(i) == '+' || s.charAt(i) == '-'))
            {
                if (s.charAt(i - 1) != 'e')
                    return false;
            }
            else 
                return false;
        }
        return num;
    }
}

No comments:

Post a Comment