Easy clean solution on JavaScript with explanation of idea


  • 1
    A

    I've started with all possible input and figured out that in general we have 2.5 cases:

    1. Integer number, name it <int>, like 000 1123 -324 +424.
    2. Float number (with optional dot), name it <int_or_float>, like any previous example joined with cases like 0.00 .1123 -.324 +.424 3.
    3. Scientific notation, like 123e45 which in fact brings down to <int_or_float>e<int>

    So we need the following steps to have this problem solved:

    1. Trim a string from spaces
    2. Write a function to detect if string is <int_or_float>
    3. Extend the function with optional ability to detect if string is strictly integer <int>

    If we call this function isSimpleNumber(str, isInt), the algorithm looks like this:

    s = s.trim()
    
    if (s.includes('e')) {
     
        const parts = s.split('e')
        if (parts.length !== 2 || parts[0] === '' || parts[1] === '') return false
     
        return isSimpleNumber(parts[0]) && isSimpleNumber(parts[1], true)
        
    } else {
     
        return isSimpleNumber(s)
    }
    

    And the whole code is listed below:

    /**
     * @param {string} s
     * @return {boolean}
     */
    var isNumber = function(s) {
        'use strict'
        
        /**
         * Returns true for any string that contains digits, may contain leading sign and (for isInt === false) one dot
         * @param {string} str
         * @param {boolean} isInt Stricts validation rules to integers only
         * @return {boolean}
         */
        function isSimpleNumber(str, isInt) {
            
            let dotCount = 0
            let digitCount = 0
            let startIndex = (str[0] === '-' || str[0] === '+') ? 1 : 0
            
            for (let i = startIndex; i < str.length; ++i) {
                if (str[i] === '.') dotCount++
                if (str[i] >= '0' && str[i] <= '9') digitCount++
                if ((str[i] < '0' || str[i] > '9') && str[i] !== '.') return false
            }
            
            return digitCount > 0 && ((isInt && dotCount === 0) || (!isInt && dotCount <= 1))
        }
        
        s = s.trim()
        
        if (s.includes('e')) {
         
            const parts = s.split('e')
            if (parts.length !== 2 || parts[0] === '' || parts[1] === '') return false
         
            return isSimpleNumber(parts[0]) && isSimpleNumber(parts[1], true)
            
        } else {
         
            return isSimpleNumber(s)
        }
    };

Log in to reply
 

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