心如止水
Je n'ai pas le temps
posts - 400,comments - 130,trackbacks - 0

迭代得到Si的值,同时用set记录已经计算过的Si。如果出现1,成功;如果出现了已经出现过一次的值,失败(因为之后也不会再出现1)。
以下是我的代码:

#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 阅读(442) 评论(0)  编辑 收藏 引用 所属分类: 题目分类:基础/模拟

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理