Created
February 23, 2009 16:43
-
-
Save ioseb/69043 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ge.code.topcoder; | |
public class BinaryCode { | |
private static final String NONE = "NONE"; | |
private int toInt(char c) { | |
return Integer.parseInt(Character.toString(c)); | |
} | |
private String decode(String message, int startBit) { | |
StringBuilder decoded = null; | |
int l = message.length(); | |
int[] p = new int[l]; | |
p[0] = startBit; | |
for (int i = 0, j = 1, q = 0, p1 = 0, p2 = startBit; i < l; i++, j++, p1 = p2, p2 = q) { | |
q = toInt(message.charAt(i)) - p2 - p1; | |
if (q > 1 || q < 0) { | |
decoded = new StringBuilder(NONE); | |
break; | |
} | |
if (j < l) { | |
p[j] = q; | |
} | |
} | |
if (decoded == null) { | |
decoded = new StringBuilder(p.length); | |
for (int i = 0; i < p.length; i++) { | |
decoded.append(p[i]); | |
} | |
} | |
return decoded.toString(); | |
} | |
public String[] decode(String message) { | |
return new String[]{ | |
decode(message, 0), | |
decode(message, 1) | |
}; | |
} | |
public static void main(String[] args) { | |
BinaryCode bc = new BinaryCode(); | |
String[] result = bc.decode("12221112222221112221111111112221111"); | |
for (int i = 0; i < result.length; i++) { | |
System.out.println(result[i]); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment