263 . Ugly Number
Easy
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.
2ms:
public boolean isUgly(int num) {
if(num<=0)
return false;
while(num%2==0)
num /= 2;
while(num%3==0)
num /= 3;
while(num%5==0)
num /= 5;
return num==1;
}
264 . Ugly Number II
Medium
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.
72ms:
public int nthUglyNumber(int n) {
int ans = 0;
List<Integer> list1 = new LinkedList<Integer>();
List<Integer> list2 = new LinkedList<Integer>();
List<Integer> list3 = new LinkedList<Integer>();
list1.add(1);
list2.add(1);
list3.add(1);
for(int i = 0; i < n; i++){
ans = Math.min(Math.min(list1.get(0),list2.get(0)), list3.get(0));
if(ans == list1.get(0)) list1.remove(0);
if(ans == list2.get(0)) list2.remove(0);
if(ans == list3.get(0)) list3.remove(0);
list1.add(ans*2);
list2.add(ans*3);
list3.add(ans*5);
}
return ans;
}
13ms:
public int nthUglyNumber(int n) {
if (n <= 0)return 0;
int[] index = new int[3];
int[] uglyNumber = new int [n];
uglyNumber[0] = 1;
int min_num = 1;
int i = 1;
while (n > 1) {
min_num = Math.min(2*uglyNumber[index[0]], Math.min(3*uglyNumber[index[1]], 5*uglyNumber[index[2]]));
uglyNumber[i] = min_num;
while(2*uglyNumber[index[0]]<=min_num) index[0]++;
while(3*uglyNumber[index[1]]<=min_num) index[1]++;
while(5*uglyNumber[index[2]]<=min_num) index[2]++;
i++;
n--;
}
return min_num;
}
本文介绍了如何判断一个数是否为丑数,并提供了两种方法来找出第n个丑数。丑数是指只包含2、3、5这三个质因数的正整数。文章通过示例代码详细阐述了两种不同的算法实现。

被折叠的 条评论
为什么被折叠?



