方法一:使用set存放
用set存放不是快乐数的可能性,重点是找到循环节点(我们认为非快乐数都会进入一个循环)
class Solution
{
public:
int calculate(int n) {
int now=0;
while(n) {
now+=(n%10)*(n%10);
n=n/10;
}
return now;
}
bool isHappy(int n){
unordered_set<int> memory;
while(1){
n=calculate(n);
if(n==1) return true;
if(memory.count(n)!= 0) return false;
memory.insert(n);
}
return true;
}
};
方法二:使用快慢指针去找循环,非常巧妙
class Solution
{
public:
int calculate(int n) {
int now=0;
while(n) {
now+=(n%10)*(n%10);
n=n/10;
}
return now;
}
bool isHappy(int n){
int fast=n;
int slow=n;
do{
slow=calculate(slow);
fast=calculate(fast);
fast=calculate(fast);
}while(slow!=fast);
return slow==1;
}
};
本文介绍两种判定快乐数的方法:一种是使用set记录已计算过的数避免重复计算;另一种是使用快慢指针技巧,高效找出循环节点,判断是否为快乐数。
:快乐数&spm=1001.2101.3001.5002&articleId=106907314&d=1&t=3&u=b184fce4546f45f0983d387102c75817)
4693

被折叠的 条评论
为什么被折叠?



