leetcode202. 快乐数

暴力偷鸡

class Solution {
public:
    bool isHappy(int n) {
        if(n==1||n==7||n==1111111)return true;//测试出来的hhhh
        while(n>=10){
            int t=0,x=n;
            while(x){
                t+=(x%10)*(x%10);
                x/=10;
            }
            if(t==1)return true;
            n=t;
        }
        return false;
    }
};

快慢指针

class Solution {
public:
    int getx(int x){
        int ans=0;
        while(x){
            int t=x%10;
            ans+=t*t;
            x/=10;
        }
        return ans;
    }
    bool isHappy(int n) {
        int fast=n,slow=n;
        do{
            slow=getx(slow);
            fast=getx(fast);
            fast=getx(fast);
        }while(fast!=slow);
        return slow==1;
    }
};

哈希

class Solution {
public:
    int getx(int x){
        int ans=0;
        while(x){
            int t=x%10;
            ans+=t*t;
            x/=10;
        }
        return ans;
    }
    bool isHappy(int n) {
        unordered_map<int ,int>mp;
        ++mp[n];
        while(mp[n]<=1){
            n=getx(n);
            if(n==1)return true;
            else ++mp[n];
        }
        return false;
    }
};