码迷,mamicode.com
首页 > 移动开发 > 详细

leetcode208 happynumber

时间:2015-05-12 22:39:26      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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

leetcode208 happynumber

标签:

原文地址:http://www.cnblogs.com/alanhu/p/4498801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!