New to JS, please help me to improve it.


  • 0
    M
    var isHappy = function(n) {
        var mapRecord = {};
        while(mapRecord[n] === undefined)
        {
            mapRecord[n] = true;
            n = getNextNumber(n);
        }
        return n === 1;
    };
    
    var getNextNumber = function(n){
        var result = 0;
        while(n >= 1)
        {
            var digit = n % 10;
            result += digit * digit;
            n = (n - digit)/10;
        }
        return result;
        
    }

  • -1
    A
    var isHappy = function(n) {
        var mapRecord = {};
        while(mapRecord[n] === undefined)
        {
            mapRecord[n] = true;
            n = getNextNumber(n);
            if (n === 1) { return true; }
        }
        return false; // When mapRecord[n] equal true means there is a endless circle and n can't be a happy number.
    };
    
    var getNextNumber = function(n){
        var result = 0;
        while(n >= 1)
        {
            var digit = n % 10;
            result += digit * digit;
            n = (n - digit)/10;
        }
        return result;
    
    }
    

Log in to reply
 

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