力扣[LeetCode].202. 快乐数

在这里插入图片描述

class Solution {
    
    
public:
    //先实现一下函数
    int get(int x){
    
    
        int res=0;
        while(x){
    
    
            res +=(x%10)*(x%10);
            x/=10;
        }
        return res;    
    }
    bool isHappy(int n) {
    
    
        int fast =get(n),slow=n;
        //两个指针,fast操作一次,slow不操作
        while(fast != slow){
    
    
            fast=get(get(fast));
            //fast操作两次
            slow=get(slow);
            //slow操作一次
        }
        return fast==1;
        //最后判断是不是等于1
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45488131/article/details/108720165