Simple Javascript Solution


  • 0
    J

    Using reduce you can easily accumulate the value. The problem statement called for infinite looping, but I've added a count check to return false in that scenario.

    /**
     * @param {number} n
     * @return {boolean}
     */
    var isHappy = function(n, count) {
        if (!count) {
            var count = 0;
        }
    
        if (n === 1) {
           	return true;
        }
        
        if (count > 50) {
        	return false;
        }
       
        var happySplit = n.toString().split('');
        
        var sumSquare = happySplit.reduce(function(acc, val) {
            return acc + (Math.floor(val * val));
        }, 0);
        
        count ++;
        return isHappy(sumSquare, count);   
    };

Log in to reply
 

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