Created
December 21, 2016 15:09
-
-
Save PradeepLoganathan/70f448d7974461188795d0bc902ed84a to your computer and use it in GitHub Desktop.
Integer to String encoder
This file contains 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
public final class AlphabetEncoder | |
{ | |
private static final char[] ALPHABET = { '0', '1', '2', ...., 'z' }; | |
private static final int ENCODE_LENGTH = ALPHABET.length; | |
public static String encode(int victim) | |
{ | |
final List<Character> list = new ArrayList<>(); | |
do { | |
list.add(ALPHABET[victim % ENCODE_LENGTH]); | |
victim /= ENCODE_LENGTH; | |
} while (victim > 0); | |
Collections.reverse(list); | |
return new String(list.toArray(new char[list.size()], | |
StandardCharsets.UTF_8); | |
} | |
public int decode(final String encoded) | |
{ | |
int ret = 0; | |
char c; | |
for (int index = 0; index < encoded.length(); index++) { | |
c = encoded.charAt(index); | |
ret *= ENCODE_LENGTH; | |
ret += Arrays.binarySearch(ALPHABET, c); | |
} | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment