十進制轉36進制

package test;

import java.util.HashMap;
import java.util.Stack;

/**
 * 36進制與10進制轉換思路:
 *      一、創建HashMap類型對象用於存放數字'0'到字母'Z'36個字符值鍵對
 *      二、
 * @author Administrator
 *
 */
public class Ten2Sixty {
    //定義36進制數字
    private static final String X36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //拿到10進制轉換36進制的值鍵對
    private static HashMap<Integer,Character> tenToThirtysix = createMapTenToThirtysix();
    //定義靜態進制數
    private static int BASE = 36;
    //用來存放10轉36進制的字符串
    private static StringBuffer sb = new StringBuffer();
    private static Stack<Character> stack = new Stack<>();

    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;
    }
    
    /**
     * 用遞歸來實現10 to 36
     * @param iSrc
     * @return
     */
    public static String DeciamlToThirtySix(int iSrc) {

        while(iSrc != 0){
            int b = iSrc % BASE;
            int a = iSrc / BASE;
            stack.push(tenToThirtysix.get(b));
            iSrc = a;
        }
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        int a = 15;
        String s = DeciamlToThirtySix(a);
        System.out.println(s);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章