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.
0是一个spcial case, 当num>1的时候,分别对它进行检测,如果是丑数的话最后的结果应该是1.(不知道为啥一开始最后的判断条件写成了0)
class Solution {
public:
bool isUgly(int num) {
if(num == 0) return false;
while(num > 1){
if(num % 2 == 0) num /= 2;
else if(num % 3 == 0) num /= 3;
else if(num % 5 == 0) num /= 5;
else return false;
}
return num == 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, and n does not exceed 1690.
class Solution {
public:
int nthUglyNumber(int n) {
if(n <= 0) return false;
if(n == 1) return 1;
vector<int> dp(n);
dp[0] = 1;
int idx2 = 0, idx3 = 0, idx5 = 0;
for(int i = 1; i != n; ++ i){
dp[i] = min(dp[idx2]*2, min(dp[idx3]*3, dp[idx5]*5));
if(dp[i] == dp[idx2]*2) idx2++;
if(dp[i] == dp[idx3]*3) idx3++;
if(dp[i] == dp[idx5]*5) idx5++;
}
return dp[n-1];
}
};