原文题目:
读题:
题目很简单,将整数的每位取平方相加看是否等于1,如果死循环那么就返回False
//方法一
class Solution
{
public:
int getResult(int n)
{
int temp = n;
int result = 0;
while(temp)
{
result += (temp%10)*(temp%10);
temp = temp/10;
}
return result;
}
bool isHappy(int n)
{
int re = 0;
int count = 0;
re = getResult(n);
if(re == 1)
{
return TRUE;
}
else
{
while(re!=1)
{
re = getResult(re);
count++;
if(count > 30) //假设30次后仍然未到1,则返回False,这里其实不是很合理。
{
return FALSE;
}
}
}
return TRUE;
}
};
//方法二
class Solution {
public:
int sq_sum(int n) {
int sq = 0;
while (n > 0) {
sq += pow(n % 10, 2);
n = n/10;
}
return sq;
}
bool isHappy(int n) {
int num = n;
unordered_set<int> map; //C++ 11新增
while (num > 0) {
map.insert(num);
num = sq_sum(num);
if (num == 1)
return true;
if (map.count(num)) //如果在set中找到num,说明存在死循环,那么返回False
return false;
}
}
};