-
-
Save Sailfishc/f89b732641ae713b488ea797a9b2a56c to your computer and use it in GitHub Desktop.
Java 短链接生成算法
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 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