这题本来想找数学规律来着,但是没有找到。。(有路过的大牛还请指导)
就根据题目来看,要么出现1,返回true退出;要么在循环的过程中出现了以前出现的数(这点题目中给出了描述or it loops endlessly in a cycle which does not include 1. )。所以将过程中出现的数存入set中,每次插入 的时候,如果发现size大小没有变,那么一定是插入了重复的数,break;这样进行了大量的优化。
class Solution {
public:
bool isHappy(int n) {
set <int> st;
st.clear();
while(1)
{
int sum=0;
while(n)
{
int k=n%10;
sum+=k*k;
n/=10;
}
n=sum;
if(n==1)
return true;
int pre=st.size();
st.insert(n);
int cur=st.size();
if(cur==pre)
return false;
else
continue;
}
}
};