Use a set to save all visited numbers. If the new number is already in the set, then it will not end. And if the new number is 1, return true.
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> set;
while(set.find(n)==set.end())
{
set.insert(n);
n=calculate(n);
if(n==1)
return true;
}
return false;
}
int calculate(int n)
{
int res=0;
while(n)
{
res+=(n%10)*(n%10);
n/=10;
}
return res;
}
};