leetcode208 happynumber

19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

 

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);
}

posted @ 2015-05-12 22:09  默默成长  阅读(109)  评论(0编辑  收藏  举报