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.
class Solution {
public:
int nthUglyNumber(int n) {
int* uglyNum = new int[n];
uglyNum[0] = 1;
int* ptr_2 = uglyNum, *ptr_3 = uglyNum, *ptr_5 = uglyNum;
for (int i = 1; i < n; i++)
{
uglyNum[i] = min(*ptr_2 * 2, *ptr_3 * 3, *ptr_5 * 5);
if (uglyNum[i] == *ptr_2 * 2)
ptr_2++;
if (uglyNum[i] == *ptr_3 * 3)
ptr_3++;
if (uglyNum[i] == *ptr_5 * 5)
ptr_5++;
}
return uglyNum[n - 1];
}
int min(int a, int b, int c)
{
int temp = a < b ? a : b;
return temp < c ? temp : c;
}
};