1. 题目描述
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个ugly number(能且仅能被2,3,5整除的数)
2. 解题思路
ugly number = 2^m*3^n*5^k
所以我们需要根据m,n,k的变化来得到ugly number的从小到大的序列
*2 | *3 | *5 |
---|---|---|
2 | 3 | 5 |
2*2 | 3 | 5 |
2*2 | 2*3 | 5 |
3*2 | 2*3 | 5 |
3*2 | 2*3 | 2*5 |
4*2 | 3*3 | 2*5 |
5*2 | 3*3 | 2*5 |
5*2 | 4*3 | 2*5 |
6*2 | 4*3 | 3*5 |
… | … | … |
当当前值为三个值中最小值时,指向的值在数组中后移一位
3. Code
class Solution {
public:
int min(int a, int b)
{
return a<b ? a:b;
}
int nthUglyNumber(int n) {
// num = 2^m*3^n*5^k;
int* numbers = new int[n]; //保存所有1-n的丑数
numbers[0] = 1; // 第一个丑数是1
int n1(0),n2(0),n3(0);
int a(0),b(0),c(0);
// 一次循环获得一个当前满足条件的最小值
for(int i(1); i < n; ++i)
{
n1 = numbers[a]*2;
n2 = numbers[b]*3;
n3 = numbers[c]*5;
int curMin = min(min(n1,n2),n3);
numbers[i] = curMin;
// 并列关系,在相同数值时一起向后移动
if(n1 == curMin)
a++;
if(n2 == curMin)
b++;
if(n3 == curMin)
c++;
}
return numbers[n-1];
}
};