【数据结构】算法 Happy Number 快乐数

Happy Number 快乐数

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

判断一个数是否是快乐数

Input: n = 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

通过链表思路,判断是否有环

int32的的最大是也不会超过2^32,从这个角度,在该范围内能够出现的最大快乐数规则来计算1999999999平方和为730.

所以超过730次后一定会有重复。

快慢指针

p,q都从head出发,p指针一次向后走一步,q向后走2步,

getnext计算的是x的各位平方和,然后迭代。当p,q不相等并且q!=1时继续循环。最后当q=1或者这个迭代出现循环时结束。该思路利用的是链表的环思维。但是没有使用链表结构

class Solution {
    public boolean isHappy(int n) {
        int p  = n ;
        int q = n;
        do{
            p = getnext(p);
            q = getnext(getnext(q));
        }while(q!=p&&q!=1);
        return q ==1;
    }
    public int getnext(int x){
        int z =0;
        while(x>0){
            z+=(x%10)*(x%10);
            x /=10;
        }
        return z;
    }
}
原文地址:https://www.cnblogs.com/dreamtaker/p/14509111.html