[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;
【具体代码如下】
【个人总结】
这道题在hash数组的大小上有待研究,通过测试,大小的临界值为367,凡是大于等于367的,都能AC,小于的都不能通过。这应该跟测试的数据有关,测试的数据影响中间值,中间值存放在hash数组中。从另一个方面来看,从int型数的最大取值上来看,hash的大小应该更大些。
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的大小应该更大些。
相关文章推荐
- Objective-C 【单个对象内存管理(野指针&内存泄露)】
- Objective-C 【单个对象内存管理(野指针&内存泄露)】
- Android-Property_Animation介绍及基本实现(属性动画)
- Objective-C 【内存管理&手动内存管理 综述】
- Objective-C 【内存管理&手动内存管理 综述】
- JDK8运行Applet
- Android实战简易教程-第四十八枪(App引导页面效果实现)
- android:如何从照片中获取拍摄地址信息
- Django之第一个app<15>
- Android视频播放器mediaplayer
- Android ImageView ScaleType 图解
- android系统service组件的线程关系
- Permission is only granted to system apps
- Java中Object类
- Android 5.1 Phone 挂断电话流程分析
- SQLite_Android
- 【Android基础】-Service组件使用详解
- SSHDroid(SSH Server for Android)通过PC或命令连接android
- Android手机做无线中继路由器
- Android - SimpleAdapter适配器支持的组件及Listview模拟下载