[leetcode]Happy Number C语言

【题目】
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
【题目分析】
这道题关键是当一个数不是happy number的时候的判断,因为如果不及时返回false,那么就会一直处于死循环的状态。用数组来存储中间值,当中间值多次出现时,我们把它理解为陷入死循环了,此时返回false;
【具体代码如下】

int nn(int n)
{
    int total=0;
    int i=n/10;
    int j=n%10;
    while(i>0)
    {  
        total+=j*j;

        j=i%10;
        i=i/10;
    }
    total+=j*j;

    return total;
}
int  isHappy(int n) {
    int happy=nn(n);
    int hash[370]={0};
    while((happy!=1))
    {
        if(happy<=1000)
        {
            hash[happy]++;
            if(hash[happy]>10)
              return false;
        }
        happy=nn(happy);
    }
    return true;
  }

【个人总结】
这道题在hash数组的大小上有待研究,通过测试,大小的临界值为367,凡是大于等于367的,都能AC,小于的都不能通过。这应该跟测试的数据有关,测试的数据影响中间值,中间值存放在hash数组中。从另一个方面来看,从int型数的最大取值上来看,hash的大小应该更大些。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值