class Solution {
public:
bool isHappy(int n) {
set<int> s;
while(n){
int t = 0;
while(n){
t += (n%10) * (n%10);
n = n/10;
}
n = t;
if(s.count(t)) break;
else s.insert(n);
}
return n == 1;
}
};
每个数都存下来,如果重复,则会进入死循环,返回false,这里采用set这种数据类型。
class Solution {
public:
bool isHappy(int n) {
int sum=0,yu;
vector<int> vec;
vector<int>::iterator it;
while(sum !=1)
{
sum =0;
while(n!=0)
{
yu = n%10;
sum = sum + yu*yu;
n = n/10;
}
it=find(vec.begin(),vec.end(),sum);
if (it!=vec.end())
{
return false;
}
else
{
vec.push_back(sum);
n =sum;
}
}
return true;
}
};
方法一样,这里采用vector