知识点

模拟,STL(SET判断存在性)

思路

我们可以发现,如果出现n按照操作变不成1的情况,那一定是陷入了循环。所以我们可以使用set来维护n出现过的所有变化情况,若出现重复出现的情况,则返回FALSE 否则返回TRUE。

代码

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return bool布尔型
     */
    bool isHappy(int n) {
        // write code here
        set<int>set;
        while(n!=1)
        {
            int t=0;
            int s=n;
            while(s)
            {
                t+=(s%10)*(s%10);
                s/=10;
            }
            if(set.count(t))return false;
            else set.insert(t);
            n=t;
        }
        return true;
    }
};