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 读写效率是最高的,
//并不需要对数据进行排序,而且数据不重复
unordered_set<int> set;
while(1){
int sum = getSum(n);
if(sum == 1){
return true;
}
//若sum在set中已经有过,说明已经数字已经进入无限循环
//eg: 2 4 16 37 58 89 145 42 20 4 16
if(set.find(sum) != set.end()){
return false;
}else{
set.insert(sum);
}
n = sum;
}
}
};