LeetCode.263(264) UglyNumber&UglyNumber II
来源:互联网 发布:标志设计软件 编辑:程序博客网 时间:2024/06/05 05:37
题目263:
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 6, 8
are ugly while 14
is not ugly since it includes another prime factor 7
.
Note that 1
is typically treated as an ugly number.
class Solution { public boolean isUgly(int num) { //判断一个数是否是丑数(只能被2、3、5的正数),注意:1属于典型的丑数. if(num<=0)return false; while(num!=1){ if(num%5==0){ num/=5; }else if(num%3==0){ num/=3; }else if(num%2==0){ num/=2; }else{ return false; } } return true; }}
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, and n does not exceed 1690.
class Solution { public int nthUglyNumber(int n) { //找出第n个丑数(只能被2、3、5整除的正数),1是典型的丑数 //注意:不能使用逐个求出丑数,容易超时(n不超过1690即为Integer.MAX_VALUE) int [] uglyNumber=new int[n]; //规律为:the first one, which is 1. Then //k[1] = min( k[0]x2, k[0]x3, k[0]x5). The answer is k[0]x2. So we move 2's pointer to 1. Then we test: //k[2] = min( k[1]x2, k[0]x3, k[0]x5). And so on. int index2=0,index3=0,index5=0; uglyNumber[0]=1; for(int i=1;i<n;i++){ uglyNumber[i]=Math.min(uglyNumber[index2]*2,Math.min(uglyNumber[index3]*3,uglyNumber[index5]*5)); //找出最小的uglyNumber if(uglyNumber[i]==uglyNumber[index2]*2)index2++; if(uglyNumber[i]==uglyNumber[index3]*3)index3++; if(uglyNumber[i]==uglyNumber[index5]*5)index5++; } return uglyNumber[n-1]; }}
阅读全文
0 0
- LeetCode.263(264) UglyNumber&UglyNumber II
- leetcode uglynumber
- UglyNumber
- UglyNumber
- 题解LeetCode UglyNumber
- (go语言)263.uglynumber
- [leetcode 263 264]Ugly Number I II
- leetcode 263&264: Ugly Number I & II
- [Leetcode] #263#264 Ugly Number I & II
- Leetcode 264(Ugly Number II)
- leetCode #264 Ugly Number II
- leetcode 264: Ugly Number II
- LeetCode(264)Ugly Number II
- [Leetcode 264] Ugly Number II
- Leetcode 264 : Ugly Number II
- leetcode 264 : Ugly Number II
- LeetCode 264: Ugly Number II
- LeetCode 264 Ugly Number II
- [DevExpress使用随笔]之licenses.licx的处理
- 【用例】
- org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils的区别
- 自然语言处理的十个发展趋势
- 训练集噪声对于深度学习的影响
- LeetCode.263(264) UglyNumber&UglyNumber II
- UGUI_Canvas Group应用之三制作一组无法交互的UI元素
- strut2 set与get方法识别的是标签name
- switch语句
- centos 下nginx安装
- Linux网络编程服务器模型选择之并发服务器(上)
- line-height参数,数值百分比的区别
- 阿里云oss存储(python+oss实现定时备份到阿里云)
- win7下 ActiveMQapache-activemq-5.13.3+jdk7以上环境安装部署