题目描述

给定一个十进制数M,以及需要转换的进制数N。将十进制数M转化为N进制数

 

示例1

输入

7,2

返回值

"111"
public class BinaryTest {
    public static void main(String[] args) {
        BinaryTest binaryTest = new BinaryTest();

        System.out.println(binaryTest.solve(-4,3));
    }

    /**
     * 进制转换
     * @param M int整型 给定整数
     * @param N int整型 转换到的进制
     * @return string字符串
     */
    public String solve (int M, int N) {

        StringBuilder sb = new StringBuilder();
        int t = M;
        int res = Math.abs(M);

        char[] cs = chs();

        do{
            M = res;
            sb.append(cs[M%N]);
        }while((res = M/N) != 0);

        return t > 0 ? sb.reverse().toString() : sb.append("-").reverse().toString();

    }

    private char[] chs(){
        char[] cs = new char[16];
        for (int i = 0; i < 10; i++) {
            cs[i] = (char)('0'+i);
        }

        for (int i = 10; i < 16; i++) {
            cs[i] = (char)('A'+(i-10));
        }

        return cs;
    }
}