https://leetcode.com/problems/ugly-number/
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.
class Solution {
public:
bool isUgly(int num) {
if(num <= ) return false;
if(num == ) return true; while(num% == ){
num/=;
if(num == ) return true;
}
while(num% == ){
num/=;
if(num == ) return true;
}
while(num% == ){
num/=;
if(num == ) return true;
}
return false;
}
};
leetcode 263: Ugly Numbers
https://leetcode.com/problems/ugly-number-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.
Hint:
- The naive approach is to call
isUgly
for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. - An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
- The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3
class Solution {
public:
int nthUglyNumber(int n) {
if(n <= ) return n; vector<long long> dp(n+, );
for(int i=;i<=;++i) dp[i] = i; for(int i=;i<=n;++i) {
long long Min = numeric_limits<long long>::max();
for(int pre=;pre<=i-;++pre) {
if(dp[pre]* > dp[i-]) {Min = min(Min, dp[pre] * ); continue;}
else if(dp[pre] * > dp[i-]) {Min = min(Min, dp[pre] * );continue;}
else if(dp[pre] * > dp[i-]) Min = min(Min, dp[pre] * );
}
dp[i] = Min;
} return dp[n];
}
};
leetcode 264: Ugly Numbers II