Javascript solution. Short and commented


  • -2
    E
    /**
     * @param {number} n
     * @return {boolean}
     */
    var isHappy = function(n) {
        var sqrSum=n
            ,nary
            ,sequence=[]
            ,cycle=false
            ,parseF=function(n) { return parseInt(n); }
            ,sqrF=function(n) { return n*n; };
        while(!cycle) { // until a cycle is found or the number is reduced to 1
            nary=sqrSum.toString().split("").map(parseF); // for splitting the digits
            sqrSum=nary.map(sqrF).reduce((prev,curr)=>prev+curr); // get the square sum
            if(sqrSum===1) { return true; } // if the square sum is 1, return true
            else { // otherwise, check if there's a cycle found. If an element already
            // exists in the array, there is a cycle
                if(sequence.indexOf(sqrSum)<0) sequence.push(sqrSum);
                else cycle=true;
            }
        }
        return false;
    };

Log in to reply
 

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