使用哈希表来进行循环检测,如果出现了循环,则返回false
class Solution {public:unordered_map<int,int> hash;int fun(int x){int res = 0;while(x){res += (x%10)*(x%10);x /= 10;}return res;}bool isHappy(int n) {int t = n;while(t != 1&& !hash[t] ){hash[t]++;t = fun(t);}return t==1;}};
