Happy number-- recursive solution

Title description:

Write an algorithm to determine whether a number n is a happy number.

"Happy Number" is defined as:

For a positive integer, each time the number is replaced by the sum of the squares of the digits in each position.
Then repeat this process until the number becomes 1, or it may be an infinite loop but it never becomes less than 1.
If the result of this process is 1, then the number is a happy number.
Returns true if n is a happy number; otherwise, returns false.

Example 1:

Input: n=19
Output: true
Explanation:
12+92=82
82+22=68
62+82=100
12+02+02=1
Example 2:

Input: n = 2
Output: false

Source: LeetCode

 Problem-solving ideas: recursive solution

var isHappy = function(n) {
    if(n>=2&&n<=9) {
        if(n==7) return true
        return false
    }
    let newN = n.toString().split("")
    let sum = 0
    for(let i = 0; i<newN.length;i++){
        sum += (newN[i]*1)*(newN[i]*1)
    }
    if(sum == 1) return true
    return isHappy(sum)
};

 

Guess you like

Origin blog.csdn.net/m0_73334325/article/details/131224221