标签:
19 is a happy number
class Solution {
public:
bool isHappy(int n) {
int sum=0;//每次循环的和
bool hasAppear[810];//最多可能出现数的个数
memset(hasAppear, 0, sizeof(hasAppear));//将该数组初始化为0
do{
sum=0;//每次计算和之前
while(n){
int t=n%10;
sum=sum+t*t;
n=n/10;
}
n=sum;
if(sum==1) {return 1;break;}
else if(hasAppear[sum]==1){return 0;break;}
hasAppear[sum]=1;
}while(sum);
}
};
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main(){
int n;
cin>>n;
int sum=0;
bool hasAppear[10000];
memset(hasAppear, 0, sizeof(hasAppear));
do{
sum=0;
while(n){
int t=n%10;
sum=sum+t*t;
n=n/10;
}
cout<<"sum="<<sum<<endl;
n=sum;
cout<<"n="<<n<<endl;
if(sum==1) {cout<<"happy"<<endl;return 1;break;}
else if(hasAppear[sum]==1){cout<<"unhappy"<<endl;return 0;break;}
hasAppear[sum]=1;
cout<<"hasAppear["<<sum<<"]="<<hasAppear[sum]<<endl;
}while(sum);
}
标签:
原文地址:http://www.cnblogs.com/alanhu/p/4498801.html