-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnary.java
More file actions
87 lines (69 loc) · 1.66 KB
/
Unary.java
File metadata and controls
87 lines (69 loc) · 1.66 KB
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
/*
* Author: Robin Péricé (2018)
*/
package solutions.practice.classicPuzzles.easy;
import java.util.Scanner;
import common.ISolution;
public class Unary implements ISolution {
@Override
public String solve(final Scanner in) {
final String input = in.nextLine();
final String strToBin = strToBin(input);
final StringBuilder result = new StringBuilder();
final char[] chars = strToBin.toCharArray();
int i = 0;
while (i < chars.length) {
char current = chars[i];
if (current == '1') {
result.append("0 0");
if (i >= chars.length - 1) {
break;
}
char next = chars[i + 1];
while (current == next) {
result.append("0");
i++;
if (i >= chars.length - 1) {
break;
}
current = chars[i];
next = chars[i + 1];
}
} else {
result.append("00 0");
if (i >= chars.length - 1) {
break;
}
char next = chars[i + 1];
while (current == next) {
result.append("0");
i++;
if (i >= chars.length - 1) {
break;
}
current = chars[i];
next = chars[i + 1];
}
}
result.append(" ");
i++;
}
char lastChar = result.charAt(result.length() - 1);
if (' ' == lastChar) {
result.deleteCharAt(result.length() - 1);
}
return result.toString();
}
private String strToBin(final String s) {
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (int j = 0; j < bytes.length; j++) {
int val = bytes[j];
for (int i = 0; i < 7; i++) {
val <<= 1;
binary.append((val & 128) == 0 ? 0 : 1);
}
}
return binary.toString();
}
}