短網址演算法——之 10進位制與62進位制轉換
阿新 • • 發佈:2019-01-28
看了網上的短網址演算法,表示很有意思,其中最中意的還是永遠不重複的短網址演算法。
步驟:
1,準備一個被打亂的陣列,存放A-Za-Z0-9這62個字元
2.預先產生一個網址ID,將這個ID通過 _10_to_62 解析轉換成62進位制的短網址符。
3.儲存ID,短網址code,頁面URL
演算法如下,很簡單,時間效率也比較高,甚至,有了儲存的ID,要不要儲存短網址code都無所謂,
這個演算法時間複雜度本來就是n,而一般的短網址長度也就1~7位,時間複雜度也可以算作O(1)常量了。import java.util.Stack;
/**
* @author Administrator
*
*/
public class Main {
public static void main(String[] args) {
System.out.println(36526445);
System.out.println(_10_to_62(36526445));
System.out.println(_62_to_10(_10_to_62(36526445)));
}
public static final char[] array={'q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','0','1','2','3','4','5','6','7','8','9','Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'};
public static String _10_to_62(long number){
Long rest=number;
Stack<Character> stack=new Stack<Character>();
StringBuilder result=new StringBuilder(0);
while(rest!=0){
stack.add(array[new Long((rest-(rest/62)*62)).intValue()]);
rest=rest/62;
}
for(;!stack.isEmpty();){
result.append(stack.pop());
}
return result.toString();
}
public static long _62_to_10(String sixty_str){
int multiple=1;
long result=0;
Character c;
for(int i=0;i<sixty_str.length();i++){
c=sixty_str.charAt(sixty_str.length()-i-1);
result+=_62_value(c)*multiple;
multiple=multiple*62;
}
return result;
}
private static int _62_value(Character c){
for(int i=0;i<array.length;i++){
if(c==array[i]){
return i;
}
}
return -1;
}
}