leetCode刷题记录30_202_Happy Number

/*****************************************************问题描述*************************************************
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the 
number by the sum of the squares of its digits, and repeat the process until the number equals 1 
(where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for 
which this process ends in 1 are happy numbers.
Example: 
    Input: 19
    Output: true
    Explanation: 
        12 + 92 = 82
        82 + 22 = 68
        62 + 82 = 100
        12 + 02 + 02 = 1
寻找幸运数字,将一个数各位数字的平方相加得到一个新数,然后新数重复上面操作,最后结果如果得到1就是幸运数
/*****************************************************我的解答*************************************************
//所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。
/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    var squareNum = function(number){
        var sum = 0;
        var numArray = [];
        do
        {
            numArray.push(number % 10);
            number = parseInt(number / 10);
        }while(number != 0);
        for(var index = 0; index < numArray.length; index++)
        {
            sum += numArray[index] * numArray[index];
        }    
        return sum;
    };
    if(n == 0)
    {
        return false;
    }    
    while(true)
    {
        if(n == 1)
        {
            return true;
        }    
        if(n == 4)
        {
            return false;
        }    
        n = squareNum(n);
    }    
};
console.log(isHappy(19));

猜你喜欢

转载自blog.csdn.net/gunsmoke/article/details/87921123