-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUglyNumbers.java
More file actions
38 lines (30 loc) · 775 Bytes
/
UglyNumbers.java
File metadata and controls
38 lines (30 loc) · 775 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.TreeSet;
public class UglyNumbers {
static TreeSet<Integer> vals = new TreeSet<Integer>();
int kthUlgy(int k) throws IndexOutOfBoundsException{
addVals(k);
Object[] uglies = vals.toArray();
return (int) uglies[k-1];
}
void addVals(int k){
int x = 1;
while(k > 0){
vals.add(x * 2);
vals.add(x * 3);
vals.add(x * 5);
k--;
x++;
while(!vals.contains(x)) x++; //there are ways to skip numbers
}
}
public static void main(String[] args){
vals.add(1);
UglyNumbers chart = new UglyNumbers();
//System.out.println(chart.kthUlgy(3));
//System.out.println(chart.kthUlgy(4));
for(int i = 1; i< 25; i++){
System.out.println(chart.kthUlgy(i));
}
//correctly prints out the first 24 ugly numbers
}
}