题目描述
思路
首先看题干,发现判定条件中有可能会出现无限循环的情况,所以我想到可以建立一个哈希表,每次都将新的sum与旧的sum比对,如果不存在,则插入,如果存在则证明进入无限循环情况。遂返回false。
代码实现
class Solution {
public:
int getsum(int n)
{
int sum=0;
while(n!=0)
{
sum+=(n%10)*(n%10);
n=n/10;
}
return sum;
}
bool isHappy(int n)
{
//题干说无限循环,所以找到突破口,用哈希表来保存每次的和
unordered_set<int> temp;
while(true)
{
int sum=getsum(n);
if(sum==1)
{
return true;
}
if(temp.find(sum)!=temp.end())
{
return false;
}
else
{
temp.emplace(sum);
}
n=sum;
}
}
};
总结
这道题挺考验对流程的把握,尤其是拆分数字求每位的平方。使用了迭代的思想,不断对数字求模并更新。