forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnaryCoding.java
More file actions
33 lines (29 loc) · 720 Bytes
/
UnaryCoding.java
File metadata and controls
33 lines (29 loc) · 720 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
/**
* Unary coding
*
* @author Atom
*
*/
public class UnaryCoding {
public static final char UNARY_SYMBOL = '1';
public static final char END_SYMBOL = '0';
/**
* Represents a natural number n by repeating n times an arbitrary symbol followed by another arbitrary symbol.
*
* @param x The number to be encoded
* @return A string with the coded number
*/
public static String unaryCoding(final int x) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < x; i++) {
sb.append(UNARY_SYMBOL);
}
sb.append(END_SYMBOL);
return sb.toString();
}
public static void main(String[] args) {
for (int i = 0; i < 15; i ++) {
System.out.println(i + ": " + unaryCoding(i));
}
}
}