AC Java solution TDD style

  • 0

    So embarrassed of myself that I feel a bit funny with this AC solution.
    I employed the very nice Test Driven Development.. and this is what you get.
    I am amazed by those DFA solutions, good job..

    class Solution {
        public boolean isNumber(String s) {
            String x = s.trim();
            if (!x.matches("[-+0-9.a-fA-F]+"))
                return false;
            x = x.toLowerCase();
            if (!x.startsWith("0x")) {
                if (!x.matches("[-+0-9.e]+"))
                    return false;
                if (x.matches("[-+0-9.]+")) {
                    if (x.matches(".*\\..*")) {
                        // has dot
                        if (x.matches("[-+]?[0-9]*.[0-9]+")
                            return true;
                            return false;
                    } else { // no dot
                        if (x.matches("[-+]?[0-9]+"))
                            return true;
                            return false;
                } else { // has e.
    //                System.out.println(x);
                    if (x.matches("[-+]?[0-9]+e[-+]?[0-9]+") ||
                            x.matches("[-+]?[0-9]+\\.[0-9]*e[-+]?[0-9]+") ||
                            ) {
                        return true;
                    } else {
                        return false;
            } else { //16bit
            return true;

    Test cases from my test class..

                check(1, one().isNumber("0"));
                check(2, one().isNumber(" 0.1 "));
                check(3, !one().isNumber("abc"));
                check(4, !one().isNumber("1 a"));
                check(5, one().isNumber("2e10"));
                check(6, !one().isNumber("e"));
                check(7, !one().isNumber("."));
                check(8, one().isNumber(".1"));
                check(9, one().isNumber("3."));
                check(10, one().isNumber("-3."));
                check(11, !one().isNumber("2-3"));
                check(12, one().isNumber("+.8"));
                check(13, one().isNumber("45.e3"));
                check(14, !one().isNumber(".e1"));
                check(15, one().isNumber(".2e11"));
                check(16, one().isNumber("-.2e11"));
                check(17, !one().isNumber("+0e-"));
                check(18, one().isNumber(" 005047e+6"));
                check(19, one().isNumber("1.38354e+8"));

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.