您的位置:首页 > 移动开发

leetcode 202: Happy Number

2015-08-26 12:20 429 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: