《leetCode》:Ugly Number II
来源:互联网 发布:女强人老婆知乎 编辑:程序博客网 时间:2024/06/03 19:54
题目
Write a program to find the n-th ugly number.Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.Note that 1 is typically treated as an ugly number.
题目大意:求第n个丑数,其中1为第一个丑数。丑数的定义为:只含有2、3、5因子其中一个或几个的数就是丑数。
思路
丑数:利用递归来求解即可
下一个丑数一定是由前面的丑数乘以 2/3/5大于当前丑数且最小的那个。
此题比较简单,这是第三次遇到这个题了。
/*2015年11月13日19:18:39 */#include<stdio.h>#include<stdlib.h>#include<string.h>//函数的功能:返回三个数中的最小值 int my_min(int a,int b,int c){ if(a<=b&&a<=c){ return a; } else if(b<=c){ return b; } else{ return c; }}int nthUglyNumber(int n) { if(n<1){ return 0; } //开辟n个空间来存储结果 int *result=(int *)malloc(n*sizeof(int)); if(result==NULL) exit(EXIT_FAILURE); memset(result,0,n*sizeof(int)); result[0]=1; int cur=1;//用来指向当前result数组中即将保存 下一个丑数的位置 //三个指针,分别指向 下一个丑数的候选值的指针。 int *p2=result; int *p3=result; int *p5=result; while(n>1){ int min=my_min((*p2)*2,(*p3)*3,(*p5)*5); result[cur]=min; cur++; while((*p2)*2<=min){ p2++; } while((*p3)*3<=min){ p3++; } while((*p5)*5<=min){ p5++; } n--; } return result[cur-1]; }int main(void){ int k; while(scanf("%d",&k)!=EOF){ printf("%d\n",nthUglyNumber(k)); }}
AC结果如下:
1 0
- Leetcode -- Ugly Number II
- LeetCode: Ugly Number II
- [leetcode] Ugly Number II
- Leetcode: Ugly Number II
- [LeetCode] Ugly Number II
- LeetCode Ugly Number II
- [leetcode] Ugly Number II
- [LeetCode] Ugly Number II
- LeetCode ||Ugly Number II
- Leetcode: Ugly Number II
- leetcode:ugly Number II
- *LeetCode-Ugly Number II
- Ugly Number II -- leetcode
- LeetCode Ugly Number II
- [Leetcode] Ugly Number II
- [Leetcode] Ugly Number II
- leetcode-Ugly Number II
- [LeetCode] Ugly Number II
- MRC/ARC混编
- mysql 查看表状态信息和表定义
- 实现图片中心缩放
- VMware虚拟机与主机无法ping通的解决方案
- 双击运行jar文件没响应解决办法
- 《leetCode》:Ugly Number II
- Spiral Matrix II
- 软件工程(C编码实践篇)学习总结
- nginx服务器安装及配置文件详解
- tableViewCell的不同高度创建
- AT&T汇编(linux内核学习必须掌握)
- 了解Runtime
- http://www.kwstu.com/ArticleView/kwstu_20144118313429
- volley中ImageLoader的理解和扩张