Chinaunix首页 | 论坛 | 博客
  • 博客访问: 376765
  • 博文数量: 117
  • 博客积分: 2530
  • 博客等级: 少校
  • 技术积分: 1262
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-11 08:56
文章分类

全部博文(117)

文章存档

2015年(8)

2011年(2)

2010年(2)

2009年(16)

2008年(27)

2007年(42)

2006年(20)

我的朋友

分类: C/C++

2015-04-27 09:17:25

Happy Number


Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

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




bool isHappy(int n) {
    int a,b,c,i,j;
    b = n;
    c = 0;
    int cc[10000];
    i=0;


    while(b > 0)
    {
        i++;
        while(b>0)
        {
            a = b % 10;
            b = b / 10;
            c = c + a*a;
        }
        b = c;

        if(c==1)
        return 1;

       for(j = 0; j < i; j++)
       {

           if(cc[j] == c)
           return 0;

       }

       cc[i] = c;
       c = 0;
    }

}

阅读(501) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~