經典算法題 10進制轉換任意進制 ,並遍歷

進制按0 ~ 9、a ~ z、分別代碼0~36

public class example1 {
    public static void main(String[] args) {
        //遍歷00001到11111
        binarySystem(4,2);//四進制、兩位數

    }

    /**
     * 進制轉換並輸出
     * @param binary 幾進制
     * @param digit 數字的位數
     */
    public static void binarySystem(int binary,int digit){
        int count = 1;
        for (int i = 0; i < digit; i++) {count = count *binary;}
        for (int i = 0; i < count; i++) {
//            String s = Integer.toBinaryString(i);
            String s = Integer.toString(i,binary);
            System.out.println(getStr(digit-s.length())+s);
        }
    }
    public static String getStr(int a){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < a; i++) {
            sb.append("0");
        }
        return sb.toString();
    }
}

結果

00
01
02
03
10
11
12
13
20
21
22
23
30
31
32
33
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章