题目
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.
代码
1
public class Solution {
public int nthUglyNumber(int n){
if(n <= 0){return 0;}
int c2= 0,c3 = 0,c5 = 0;
List<Integer>list = new ArrayList<Integer>();
list.add(1);
while(list.size() != n){
int m2 = list.get(c2)* 2;int m3 = list.get(c3)*3;int m5 = list.get(c5)*5;
int min1=(m3 > m5?m5:m3);
int min2 = m2 > min1?min1:m2;
if(min2 == m2){
c2++;
}
if(min2 == m3 ){
c3++;
}
if(min2 == m5){
c5++;
}
list.add(min2);
}
return list.get(n-1);
}
}
转载请注明原文地址: https://ju.6miu.com/read-1853.html