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);
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。