以为这题是找规律,试着写了个循环,也过了。

用集合去判断出现过的数字,判断循环。

然后就根据题目中的算法模拟就好。

class Solution {
public:
bool isHappy(int n) {

set<int> s;

s.insert(n);
int k=0;
while(1){
int n2=0;
while(n){
// cout<<1;
int x=n%10;
n2+=(int)x*x;
n/=10;

}
// cout<<2;
if(n2==1) {k=2;break;}

if(s.find(n2)!=s.end()) {k=1; break;}
s.insert(n2);

n=n2;
}

if(k==1) return false;
if(k==2) return true;
}
};