Ugly Number
Problem I
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.
程序
public class Solution { public boolean isUgly(int num) { if (num <= 0) { return false; } while (num > 1) { if (num % 2 == 0) { num /= 2; continue; } if (num % 3 == 0) { num /= 3; continue; } if (num % 5 == 0) { num /= 5; continue; } return false; } return true; } }
Problem II
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.
解决思路
我们可以发现每一个子列表都是丑陋数本身(1, 2, 3, 4, 5, …) 乘以 2, 3, 5
接下来我们使用与归并排序相似的合并方法,从3个子列表中获取丑陋数。每一步我们从中选出最小的一个,然后向后移动一步。
程序
public class Solution { public int nthUglyNumber(int n) { if (n <= 0) { return 0; } List<Integer> list = new ArrayList<Integer>(); list.add(1); int i2 = 0, i3 = 0, i5 = 0; while (list.size() < n) { int n2 = list.get(i2) * 2; int n3 = list.get(i3) * 3; int n5 = list.get(i5) * 5; int m = Math.min(Math.min(n2, n3), n5); if (m == n2) { ++i2; } if (m == n3) { ++i3; } if (m == n5) { ++i5; } list.add(m); } return list.get(n - 1); } }