202. 快乐数
题目描述
题目描述

哈希集合实现
#pragma once
#include <iostream>
#include<unordered_set>
using namespace std;
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> hashset;
hashset.insert(n);
while (n != 1)
{
n = getsum(n);
if (hashset.count(n) > 0)
{
return false;
}
else
{
hashset.insert(n);
}
}
return true;
}
};
int main()
{
Solution S;
cout << "请输入需要判断的数字:";
int n;
cin >> n;
bool res = S.isHappy(n);
if (res)
{
cout << n << "是快乐数!" << endl;
}
else
{
cout << n << "不是快乐数!" << endl;
}
system("pause");
return 0;
}
运行结果

提交结果
