迭代得到Si的值,同時用set記錄已經計算過的Si。如果出現1,成功;如果出現了已經出現過一次的值,失?。ㄒ驗橹笠膊粫俪霈F1)。
以下是我的代碼:
#include<set>
#include<cstdio>
using namespace std;
int f(int x)
{
int re(0);
while(x>0)
{
int t(x%10);
re+=t*t;
x/=10;
}
return re;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
int T;
scanf("%d",&T);
for(int case_num=1;case_num<=T;case_num++)
{
int n;
scanf("%d",&n);
printf("Case #%d: %d is ",case_num,n);
set<int> r;
bool success(false);
while(true)
{
if(n==1)
{
success=true;
break;
}
else if(r.count(n)==1)
{
success=false;
break;
}
r.insert(n);
n=f(n);
}
if(success)
printf("a Happy number.\n");
else
printf("an Unhappy number.\n");
}
}
posted on 2011-05-07 16:02
lee1r 閱讀(474)
評論(0) 編輯 收藏 引用 所屬分類:
題目分類:基礎/模擬