• slow 每次走一步,fast 每次走两步。
  • 如果存在循环,快慢指针必定相遇;循环结束条件:任一指针到达 1 或者两者相遇。
  • 最后只要任何一个为 1 就是快乐数。
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return bool布尔型
     */
    int next(int n){
        int res=0;
        while(n){
            res+=(n%10)*(n%10);
            n/=10;
        }
        return res;
    }

    bool happynum(int n) {
        int slow=n,fast=n;
        do{
            slow=next(slow);
            fast=next(next(fast));
        }while(slow!=1 && fast!=1 && slow!=fast);
        return slow==1 || fast==1;
    }
};