Ugly number
Write a program to check whether a given number was an ugly number.
Ugly numbers is positive numbers whose prime factors only include 2, 3, 5 . For example, was ugly while was not 6, 8 14 ugly since it includes another prime factor 7 .
Note that's 1 typically treated as an ugly number.
Ugly number II
Write a program to find the n -th ugly number.
Ugly numbers is positive numbers whose prime factors only include 2, 3, 5 . For example, is the sequence of the first 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 10 ugly numbers.
Note that's 1 typically treated as an ugly number.
Again a small problem to find the K, the old topic re-talk.
The general idea is to minimize the current, find the number behind, and put it in the priority queue to save.
First, ugly number
1 Public classSolution {2 Public Booleanisugly (intnum) {3 if(num<=0)return false;4 if(num==1)return true;5 while(num!=1){6 if(num%2==0) num/=2;7 Else if(num%3==0) num/=3;8 Else if(num%5==0) num/=5;9 Else return false;Ten } One return true; A } -}
Second, ugly number II
1 ImportJava.util.*;2 3 Public classSolution {4 Public intNthuglynumber (intN) {5 if(n==1)return1;6 //you need to use a double to save the data, and an int will overflow7priorityqueue<double> q2 =NewPriorityqueue<double>();8priorityqueue<double> q3 =NewPriorityqueue<double>();9priorityqueue<double> Q5 =NewPriorityqueue<double>();TenQ2.offer (1.0); One DoubleMin =1; A for(inti=1;i<=n;i++){ -Min =Q2.peek (). Intvalue (); -min =!q3.isempty () &&q3.peek (). Intvalue () <min?Q3.peek (). Intvalue (): min; themin =!q5.isempty () &&q5.peek (). Intvalue () <min?Q5.peek (). Intvalue (): min; - if(min==Q2.peek (). Intvalue ()) { - Q2.poll (); -Q2.offer (min); +Q3.offer (*min); -Q5.offer (5*min); +}Else if(min==Q3.peek (). Intvalue ()) { A Q3.poll (); atQ3.offer (*min); -Q5.offer (5*min); -}Else{ - Q5.poll (); -Q5.offer (min*5); - } in } - return(int) min; to } +}
[Leetcode] Ugly number problem