题目链接:
题目描述:
思路1:哈希->unordered_set(任意输入的大数都会快速塌缩到一个小数,如果没有计算到1,最终一定会进入到4->16->37->58->...->20->4这个无限循环中)
思路2:快慢指针,fast指针每次前进两步,slow指针每次前进一步,从输入的n开始每次移动fast,slow,如果二者任意一个得到了1,则为快乐数,返回true; 如果一直没有算出1,且之后fast多走一圈与slow相遇,则存在环,只会在环里打转,不可能到1,所以不是快乐数,返回false。
题解:
哈希:
#include<iostream>
#include<unordered_set>
using namespace std;
bool isHappy(int n) {
unordered_set<int>s;
while(1){
s.insert(n);
int tem=0;
while(n){
int x=(n%10);
tem+=(x*x);
n/=10;
}
if(tem==1)return true;
if(s.find(tem)!=s.end())return false;
n=tem;
}
}
int main(){
int n; cin>>n;
if(isHappy(n))cout<<"true";
else cout<<"false";
}
快慢指针:
#include<iostream>
using namespace std;
int next(int t) {
int tem=0;
while(t){
int x=(t%10);
tem+=(x*x);
t/=10;
}
return tem;
}
bool isHappy(int n) {
int slow=n,fast=next(n);
while(1){
if(slow==1||fast==1) return true;
if(slow==fast) return false;
slow=next(slow);
fast=next(next(fast));
}
}
int main(){
int n; cin>>n;
if(isHappy(n))cout<<"true";
else cout<<"false";
}