#include<iostream>
#include<unordered_set>
using namespace std;
// 取数值各个位上的单数平方之和
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>set;
while (1)
{
int sum = getSum(n);
if (sum == 1)
{
return true;
}
// 如果sum曾经出现过,说明已经陷入无限循环了,立即return false
if (set.find(sum) != set.end())
{
return false;
}
else
{
set.insert(sum);
}
n = sum;
}
}
int main() {
int num = 82;
bool result = isHappy(num);
cout << "result:" << result << endl;
}
标签:10,set,return,int,sum,快乐,哈希,false
From: https://www.cnblogs.com/dh2021/p/16832967.html