Question

link

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.

Stats

Frequency 5
Difficulty 2
Adjusted Difficulty unsolvable
Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Solution

I am unable to solve this problem, but I found a quite good solution. I post the code below.

My code

public boolean isNumber(String s) {
    s = s.trim(); 
    if (s.length() > 0 && s.charAt(s.length() - 1) == 'e')
        return false; //avoid "3e" which is false
    String[] t = s.split("e");
    if (t.length == 0 || t.length > 2) return false;
    boolean res = valid(t[0], false);
    if (t.length > 1) res = res && valid(t[1], true);
    return res;
}

private boolean valid(String s, boolean hasDot) {
    if (s.length() > 0 && (s.charAt(0) == '+' || s.charAt(0) == '-')) 
        s = s.substring(1); //avoid "1+", "+", "+."
    char[] arr = s.toCharArray();
    if (arr.length == 0 || s.equals(".")) return false;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == '.') {
            if (hasDot) return false;
            hasDot = true;
        } else if (!('0' <= arr[i] && arr[i] <= '9'))
            return false;
    }
    return true;
}