Happy Number

 1 class Solution {
 2 public:
 3     bool isHappy(int n) {
 4         int dig[1000],cnt,ans;
 5         memset(dig,0,sizeof(dig));
 6         while(1)
 7         {
 8             ans=0;
 9             while(n)
10             {
11                 cnt=n%10;
12                 n/=10;
13                 ans+=cnt*cnt;
14             }
15             n=ans;
16             if(ans==1)return 1;
17             if(dig[ans]==0)
18                 dig[ans]=1;
19             else if(dig[ans]==1)
20                 return 0;
21         }
22     }
23 };
View Code
若是10位整数,9999999999,平方和是81,所以只需要开一个1000的数组,将每个出现过的数字记为1,就能知道有没有出现循环了
原文地址:https://www.cnblogs.com/varcom/p/4564450.html