-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitsPal.java
More file actions
45 lines (37 loc) · 737 Bytes
/
BitsPal.java
File metadata and controls
45 lines (37 loc) · 737 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
39
40
41
42
43
44
45
import java.util.TreeSet;
public class BitsPal {
static TreeSet<Integer> vals = new TreeSet<Integer>();
boolean isPal(int x){
int orig = x;
int y = 0;
while(x > 0){
y <<= 1;
y |= (x & 1);
x >>= 1;
}
if(orig==y) return true;
return false;
}
void addPal(int k){
int i = vals.size()+1;
while(vals.size() < k){
if(isPal(i)){
vals.add(i);
}
i++;
}
}
int kthPal(int k) throws IndexOutOfBoundsException{
if(k > vals.size()){
addPal(k);
return vals.last();
}
Object[] nums = vals.toArray();
return (int) nums[k];
}
public static void main(String[] args){
BitsPal pal = new BitsPal();
System.out.println(pal.kthPal(49));
System.out.println(pal.kthPal(50));
}
}