1. X进制转换成十进制-V1:
/*** 笨办法,从左往右开始* Tips:只支持正数** @param num* @param radix* @return*/private static Integer xToTenV1(String num, Integer radix) {if (num.length() == 0 || num.charAt(0) == '-') {throw new IllegalArgumentException();}String[] arrays = num.split("");int len = arrays.length;int result = 0, digit = 0, digitRadix = 1;for (int i = 0; i < len; i++) {digit = Integer.parseInt(arrays[len - 1 - i]);if (i != 0) {digitRadix *= radix;}result += digit * digitRadix;}return result;}
2. X进制转换成十进制-V2:
/*** 参照Integer.parseInt(String s,int radix) 方法* 核心逻辑:* result*=radix;* result-=digit;* return -result;* Tips:只支持正数** @param num* @param radix* @return*/private static Integer xToTenV2(String num, Integer radix) {if (num.length() == 0 || num.charAt(0) == '-') {throw new IllegalArgumentException();}String[] arrays = num.split("");int len = arrays.length;int result = 0, digit = 0;for (int i = 0; i < len; i++) {digit = Integer.parseInt(arrays[i]);result *= radix;result -= digit;}return -result;}
3. 十进制转换成X进制:
/*** Tips:只支持正数** @param mun* @param radix* @return*/public static String tenTox(int mun, int radix) {if (mun < 0) {throw new IllegalArgumentException();}StringBuilder sb = new StringBuilder();int[] array = new int[33];int index = 32;// 短除法while (mun >= radix) {array[index--] = mun % radix;mun = mun / radix;}array[index] = mun;for (int i = index; i < 33; i++) {sb.append(array[i]);}return sb.toString();}