Javascript solution with magic number 4


  • 0
    L
    var isHappy = function(n) {
        var magicNum = 4;
    
        var remainder = Math.floor(n / 10);
        while(remainder !== 0 || (remainder === 0 && n > 4)) {
            n = sumOfSquares(n);
            remainder = Math.floor(n / 10);
        }
        return n === 1 ? true : false;
    };
    
    function sumOfSquares(n) {
        var sum = 0;
    
        var i = 0;
        var quotient = n;
        while (quotient > 0) {
            i = quotient % 10;
            quotient = Math.floor(quotient / 10);
    
            sum += i * i;
        }
        
        return sum;
    }
    

Log in to reply
 

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