Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.