/*用一个Hash表记录出现过得数字。采用如下步骤获得结果:
从当前正数n开始,1)如果n == 1,则它为happy number,返回true,结束。
2)如果n != 1, 且hash表中有等于n的数字,会陷入循环,返回false,结束。
3)如果n != 1,且hash表中没有等于n的数字,则将n加入hash表,继续计算下一个n。重复。*/
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> appeared;
while(n != 1){
n = replace(n);
if(appeared.find(n) != appeared.end()) return false;
else appeared.insert(n);
}
return true;
}
int replace(int n){
int res = 0;
while(n > 0){
int tmp = n%10;
res = res + tmp * tmp;
n /= 10;
}
return res;
}
};
LeetCode之Happy Number
最新推荐文章于 2020-05-07 11:25:40 发布