Accepted Solution using JavaScript Number constructor (with comments for special cases)


  • 0
    N
    /**
     * @param {string} s
     * @return {boolean}
     */
    var isNumber = function(s) {
        // Number(..) parses whitespace/empty strings as 0
        // But leetcode expects these to be not numbers
        if (s.trim().length === 0) {
            return false;
        }
        
        // parseInt does not work for decimal strings such as '0.1'
        
        // The real deal
        var res;
        
        try {
            res = Number(s);
        } catch (e) {}
        
        return isNaN(res) ? false : true;
    };

  • 0
    C

    Using any High level language parsing number function will be a cheat for you did not fully understand how to parse a string into a number.


Log in to reply
 

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