Skip to content

Instantly share code, notes, and snippets.

@hellokaton
Created May 29, 2018 10:23
Show Gist options
  • Save hellokaton/a007ea9f7275d34d2c2d9c5d4e09ae67 to your computer and use it in GitHub Desktop.
Save hellokaton/a007ea9f7275d34d2c2d9c5d4e09ae67 to your computer and use it in GitHub Desktop.
Java 短链接生成算法
public class UrlShortener {
// private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final String ALPHABET = "mUSNcOa6hDgfnEJ1rGMPC03jv4k9RIqL2Yy7TQdH8xu5XFWwAKoZVstizlepBb";
private static final int BASE = ALPHABET.length();
public static String encode(int num) {
StringBuilder sb = new StringBuilder();
while (num > 0) {
sb.append(ALPHABET.charAt(num % BASE));
num /= BASE;
}
return sb.reverse().toString();
}
public static int decode(String str) {
int num = 0;
for (int i = 0; i < str.length(); i++)
num = num * BASE + ALPHABET.indexOf(str.charAt(i));
return num;
}
public static void main(String[] args) {
for (int i = 14776336; i < 14877336; i++) {
System.out.println(encode(i));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment