Java Solution, single pass with no split()

  • 2

    This could be condensed a bit by using String.split on the 'e' and possibly '.' characters, but I tried to use trim() as my only library call. If you're not allowed to use trim() either, you'll have to include a few more flags to check leading and trailing whitespace, but not whitespace in between.

    I solved this by using a couple flags to determine when each non-numeric number is valid. Other than digits 0-9, the only valid characters are an 'e' (which may occur at most once, and must come between two valid numbers), a single decimal point (which must come before 'e' and must have a digit 0-9 on at least one side of it), and a plus or minus sign, which may occur once, or twice if 'e' is part of the number, must be the first character at the beginning of the String or after the 'e', and must be followed by a decimal point or digit 0-9. If we encounter one of those special values while it's legal, we set some flags accordingly. I also keep a "numberEncountered" variable as a catch-all to make sure that there are no lone decimal points or plus/minus signs, as well as to make sure a number comes after 'e'.

    public boolean isNumber(String s) {
        boolean eFound = false;
        boolean eValid = false;
        boolean periodValid = true;
        boolean pmValid = true;
        boolean numberEncountered = false;
        s = s.trim();
        for(char c : s.toCharArray()) {
            if(pmValid) {
                pmValid = false;
                if(c == '+' || c == '-') continue;
            if(eValid && !eFound && c == 'e') {
                eValid = false;
                eFound = true;
                periodValid = false;
                pmValid = true;
                numberEncountered = false;
            if(periodValid && c == '.') {
                periodValid = false;
            if(c < '0' || c > '9') {
                return false;
            eValid = !eFound;
            numberEncountered = true;
        return numberEncountered;

Log in to reply

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