您的位置:首页 > 移动开发

[leetcode]Happy Number C语言

2015-08-29 21:00 435 查看
【题目】

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的大小应该更大些。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: