自定義進制轉換

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class CustomDigit {
    //方式一
    public static String Switch(int num,int base) {//num轉換的數字,base轉換的進制
        StringBuffer sb = new StringBuffer();
        String all = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String digths = all.substring(0, base);//將要轉換的進制字母對應表
        Stack<Character> s = new Stack<Character>();
        while(num != 0){
            s.push(digths.charAt(num%base));
            num/=base;
        }
        while(! s.isEmpty()){
            sb.append(s.pop());
        }
        return sb.toString();
    }
    //方式二
    public static String Switch2(int num,int radix){
    
        return Integer.toString(num,radix);
    }
    public static void main(String[] args) throws Exception, IOException {
        int num = 0;
        int base = 0;
        BufferedReader buf = null;
        System.out.print("請輸入要轉換的數字:");
        buf = new BufferedReader(new InputStreamReader(System.in));
        num = Integer.parseInt(buf.readLine());
        System.out.print("請輸入要轉換的進制:");
        buf = new BufferedReader(new InputStreamReader(System.in));
        base = Integer.parseInt(buf.readLine());
        System.out.println(Switch(num, base));
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章