1. Happy tree algorithm

For a positive integer, replace the number each time with the sum of squares of the numbers at each of its positions.

And then you repeat the process until the number is 1, or it could go on forever but it never gets to 1.

If you can change it to 1, then that number is happiness.

If you can tell that the sum of squares of a particular number has occurred before, you are stuck in an infinite loop and not a happy number. Judging a happy tree, in this way of thinking, is similar to judging whether a linked list has rings, if it does, it does not, and if it does, it is a happy tree.

1.1 Use the method similar to fast and slow pointer to judge

var isHappy = function(n) {
    let p = n; 
    let q = getValue(getValue(p));
    while(p ! = =1&& p ! == q) { p = getValue(p); q = getValue(getValue(q)); }return q === 1

    function getValue(n) {
        let sum = 0;
        while(n) {
            sum += (n % 10) * *2;
            n = Math.floor(n / 10);
        }
        return sum;
    };
};
Copy the code

1.2 Use Set to judge

var isHappy = function(n) {
    const set = new Set(a);while(n ! = =1 && !set.has(n)) {
        set.add(n);
        n = getValue(n);
    }

    return n === 1;

    function getValue(n) {
        let sum = 0;
        while(n) {
            sum += (n % 10) * *2;
            n = Math.floor(n / 10);
        }
        return sum;
    };
};
Copy the code