Java solution with one line


  • 18
    S

    return s.matches("(\\s*)[+-]?((\\.[0-9]+)|([0-9]+(\\.[0-9]*)?))(e[+-]?[0-9]+)?(\\s*)");


  • 0
    L

    First \s is not mandatory, suggest \\s*. Then ([0-9]+(\.[0-9])?), [0-9] after decimal point should not be exact one, suggest [0-9]*.Also, if it's java, i don't think \s would work...\\s would however;


  • 0
    S

    Oh no, the preview is different from my code, you are right, thanks


  • 9
    G

    Simple solution in Java without using regular expressions.

    public class Solution {
    public boolean isNumber(String s) {
        try {
            s = s.trim();
            int n = s.length();
            if ( n == 0 || (s.charAt(n-1) != '.' && (s.charAt(n-1) - '0' < 0 || s.charAt(n-1) - '0' > 9 )) ) {
                return false;
            }
            double i = Double.parseDouble(s);
            return true;
        }
        catch (NumberFormatException e) {
            return false;
        }
    }
    

    }


  • 0
    V

    parseDouble looks like cheating...


  • 0
    H

    Just want to know why there is a star instead of '+' after [0 - 9]*? If there is no digit after '.', is it a valid number?


Log in to reply
 

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