-
Notifications
You must be signed in to change notification settings - Fork 19
/
base2palindrome.java
107 lines (82 loc) · 1.79 KB
/
base2palindrome.java
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.Scanner;
public class base2palindrome {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt() + 1;
int length = 0;
int pow2 = 1;
while (pow2 <= num)
pow2 *= 2;
pow2 /= 2;
int iter = num - pow2;
if (iter < pow2 / 2)
length = 2 * (int)(Math.log(num) / Math.log(2)) - 1;
else
length = 2 * (int)(Math.log(num) / Math.log(2));
boolean[] pal = new boolean[length];
pal[0] = true;
pal[pal.length - 1] = true;
if (length % 2 == 1)
{
int mid = length / 2;
int i = 0;
for (int zax = 0; zax < iter; zax++)
{
i = 0;
while (pal[mid + i])
i++;
pal[mid + i] = true;
pal[mid - i] = true;
for (int z = mid - i + 1; z < mid + i; z++)
pal[z] = false;
}
}
else
{
int mid = length / 2;
int i = 0;
for (int zax = 0; zax < iter - (pow2 / 2); zax++)
{
i = 0;
while (pal[mid + i])
i++;
pal[mid + i] = true;
pal[mid - i - 1] = true;
for (int z = mid - i; z < mid + i; z++)
pal[z] = false;
}
}
String bin = "";
for (int i = 0; i < pal.length; i++)
if (pal[i])
bin += "1";
else
bin += "0";
System.out.println(Integer.parseInt(bin , 2));
scan.close();
}
}
/*
import java.util.Scanner;
public class base2palindrome {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int generate = scan.nextInt();
int fin = generate;
for (int i = 1; generate > 0; i++)
{
String binary = Integer.toBinaryString(i);
String binary1 = Integer.toBinaryString(Integer.reverse(i));
while (binary1.length() < 32)
binary1 = '0' + binary1;
binary1 = binary1.substring(0, binary.length());
if (binary.equals(binary1))
{
generate--;
System.out.println(i + " : " + binary + " " + binary1 + " " + binary.length() + " " + (fin - generate));
}
}
scan.close();
}
}
*/