【题目】
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。如果 n 是快乐数就返回 True ;不是,则返回 False。
来源:leetcode
链接:https://leetcode-cn.com/problems/happy-number/
【示例】
输入:19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
【方法一】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :6.2 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
void deal(int n,int &rs){
while(n){
int x=n%10;
rs+=x*x;
n/=10;
}
}
set<int> ss;
int rs=0;
bool isHappy(int n) {
while(n!=1){
if(ss.count(n))
return false;
else
ss.insert(n);
rs=0;
deal(n,rs);
n=rs;
}
return true;
}
};
【方法二:快慢指针】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :5.8 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
private:
int rs;
public:
int deal(int n){
rs=0;
while(n){
int x=n%10;
rs+=x*x;
n/=10;
}
return rs;
}
bool isHappy(int n) {
int slow=n,fast=n;
do{
slow=deal(slow);
fast=deal(fast);
fast=deal(fast);
}while(slow!=fast);
return slow==1;
}
};
【方法三】空间复杂度高
class Solution {
public:
void deal(int n,stack<int>&s){
while(n){
s.push(n%10);
n/=10;
}
}
set<int> ss;
bool isHappy(int n) {
while(n!=1){
if(ss.count(n))
return false;
else
ss.insert(n);
stack<int> s;
deal(n,s);
n=0;
while(!s.empty()){
n+=s.top()*s.top();
s.pop();
}
}
return true;
}
};