leetcode - 202. 快乐数
题目:
代码:
#include <iostream>
#include <set>
using namespace std;
/*
分为三种情况:
1、最终得到 1
2、最终进入循环
3、值越来越大,趋于无穷(不会出现,分析9(81),99(162),999(243),9999(324),...,
会发现最坏情况下,算法可能会在243以下的数字上循环)
*/
bool isHappy(int n) {
unordered_set<int> visited;
int sum = 0;
int tn;
while(n > 0){
tn = n % 10;
n = n /10;
sum += tn * tn;
if(n == 0){
n = sum;
if(!visited.count(sum)){
visited.insert(sum);
}else{
return false;
}
sum = 0;
if(n == 1){
return true;
}
}
}
return false;
}
int main(){
bool res;
int n;
cin>>n;
res = isHappy(n);
if(res){
cout<<"true";
}else{
cout<<"false";
}
return 0;
}