class Solution {
public:
int getSum(int x){
int sum=0;
while(x){
sum+=(x%10)*(x%10);
x/=10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> s;
while(1){
int ans=getSum(n);
if(ans==1){
return true;
}
if(s.find(ans)!=s.end()){
return false;
}else{
s.insert(ans);
}
n=ans;
}
}
};
答案来自代码随想录,需要了解set作用,即判断是否循环。同时要了解数字拆为各个位置平方和的写法。