有一個業務需求,只給5位編碼,數字與大寫英文字母不限,要求給出儘量多的不同編碼。
在網上找了幾篇文章,發現都不完善,不能用。一來感嘆之前作者不負責,二來感嘆爲啥這麼簡單通用的東西竟然沒有現成的。
於是自己CODE一份可用的JAVA代碼,供大家使用。直接貼完整代碼如下。
import java.util.HashMap;
/**
* 36進制與10進制轉換思路: 1、創建HashMap類型對象用於存放數字'0'到字母'Z'36個字符值鍵對
* 2. 對值模除取餘計算,遞歸調用
*
* @author xiucai.yao
*
*/
public class Ten2ThirtySix {
// 定義36進制數字
private static final String X36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 拿到36進制轉換10進制的值鍵對
private static HashMap<Character, Integer> thirysixToTen = createMapThirtysixToTen();
// 拿到10進制轉換36進制的值鍵對
private static HashMap<Integer, Character> tenToThirtysix = createMapTenToThirtysix();
// 定義靜態進制數
private static int BASE = 36;
private static HashMap<Character, Integer> createMapThirtysixToTen() {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < X36.length(); i++) {
// 0--0,... ..., Z -- 35的對應存放進去
map.put(X36.charAt(i), i);
}
return map;
}
private static HashMap<Integer, Character> createMapTenToThirtysix() {
HashMap<Integer, Character> map = new HashMap<Integer, Character>();
for (int i = 0; i < X36.length(); i++) {
// 0--0,... ..., 35 -- Z的對應存放進去
map.put(i, X36.charAt(i));
}
return map;
}
/**
* 36 to 10
*
* @param pStr
* 36進制字符串
* @return 十進制
*/
public static int ThirtysixToDeciaml(String pStr) {
if (pStr == "")
return 0;
// 目標十進制數初始化爲0
int deciaml = 0;
// 記錄次方,初始爲36進制長度 -1
int power = pStr.length() - 1;
// 將36進制字符串轉換成char[]
char[] keys = pStr.toCharArray();
for (int i = 0; i < pStr.length(); i++) {
// 拿到36進制對應的10進制數
int value = thirysixToTen.get(keys[i]);
deciaml = (int) (deciaml + value * Math.pow(BASE, power));
// 執行完畢 次方自減
power--;
}
return deciaml;
}
/**
* 10 to 36
*
* @param iSrc
* 10進制整數值
* @param pRet
* 將iSrc轉換成36進制以後的字符串
* @return 0成功,其他失敗
*/
public static int DeciamlToThirtySix(int iSrc, String pRet) {
String str = DeciamlToThirtySix(iSrc);
if (str.equals(pRet)) {
return 0;
} else {
return 1;
}
}
/**
* 用遞歸來實現10 to 36
*
* @param iSrc
* @return
*/
public static String DeciamlToThirtySix(int iSrc) {
String result = "";
int key;
int value;
key = iSrc / BASE;
value = iSrc - key * BASE;
if (key != 0) {
result = result + DeciamlToThirtySix(key);
}
result = result + tenToThirtysix.get(value).toString();
return result;
}
public static void main(String[] args) {
int x = ThirtysixToDeciaml("7VW");
System.out.println(x);
String s = DeciamlToThirtySix(10220);
System.out.println(s);
}
}