- 思路
class Solution
{
public:
// 取数值各个位上的单数之和
int getSum(int n)
{
int sum = 0;
while (n)
{
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
bool isHappy(int n)
{
unordered_set<int> tempSet;
int res=0;
while (true)
{
res = getSum(n);
if (res == 1)
{
return true;
}
// 如果这个res曾经出现过,说明已经陷入了无限循环了,立刻return false
if (tempSet.find(res) != tempSet.end())
{
return false;
}
else
{
tempSet.insert(res);//如果这个res没有出现难过,则存入set中
}
n = res;
}
}
};